使用的库是:Newtonsoft.Json 为asp.net 3.5开发的 Beta4版本,获取数据库数据用的是
Microsoft EnterpriseLibrary 4.1
其中扩展了这个库的功能,使之最适合把DataTable,DataSet,DataRow转为JSON模式
另外使用了Jquery的$.getJSON来解析后台传过来的JSON格式
另参考了:http://blog.csdn.net/dujingjing1230/archive/2009/08/28/4495008.aspx 裴旭更网友的文章
http://www.west-wind.com/Weblog/default.aspx
一个老外MVP此人专门写了一个JSON的等一系列的库,叫什么WestWind,呵呵
下面是扩展的Newtonsoft.Json几个类
DataRowConverter.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Utility { public class DataRowConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object dataRow, JsonSerializer serializer) { DataRow row = dataRow as DataRow; // *** HACK: need to use root serializer to write the column value // should be fixed in next ver of JSON.NET with writer.Serialize(object) JsonSerializer ser = new JsonSerializer(); writer.WriteStartObject(); foreach (DataColumn column in row.Table.Columns) { writer.WritePropertyName(column.ColumnName); ser.Serialize(writer, row[column]); } writer.WriteEndObject(); } /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { return typeof(DataRow).IsAssignableFrom(valueType); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer) { throw new NotImplementedException(); } } }
DataSetConverter .cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using Newtonsoft.Json; namespace Utility { public class DataSetConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object dataset, JsonSerializer serializer) { DataSet dataSet = dataset as DataSet; DataTableConverter converter = new DataTableConverter(); writer.WriteStartObject(); writer.WritePropertyName("Tables"); writer.WriteStartArray(); BindingFlags bf = BindingFlags.Public | BindingFlags.Static; foreach (DataTable table in dataSet.Tables) { converter.WriteJson(writer, table, serializer); } writer.WriteEndArray(); writer.WriteEndObject(); } /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { return typeof(DataSet).IsAssignableFrom(valueType); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer) { throw new NotImplementedException(); } } }
DataTableConverter.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Utility { public class DataTableConverter : JsonConverter { /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param> /// <param name="value">The value.</param> public override void WriteJson(JsonWriter writer, object dataTable, JsonSerializer serializer) { DataTable table = dataTable as DataTable; DataRowConverter converter = new DataRowConverter(); writer.WriteStartObject(); writer.WritePropertyName("Rows"); writer.WriteStartArray(); foreach (DataRow row in table.Rows) { converter.WriteJson(writer, row,serializer); } writer.WriteEndArray(); writer.WriteEndObject(); } /// <summary> /// Determines whether this instance can convert the specified value type. /// </summary> /// <param name="valueType">Type of the value.</param> /// <returns> /// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type valueType) { return typeof(DataTable).IsAssignableFrom(valueType); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer) { throw new NotImplementedException(); } } }
Serialize.cs
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Utility { public class Serialize { public string Serializer(object value) { Type type = value.GetType(); Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); json.NullValueHandling = NullValueHandling.Ignore; json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; if (type == typeof(DataRow)) json.Converters.Add(new DataRowConverter()); else if (type == typeof(DataTable)) json.Converters.Add(new DataTableConverter()); else if (type == typeof(DataSet)) json.Converters.Add(new DataSetConverter()); StringWriter sw = new StringWriter(); Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.QuoteChar = '"'; json.Serialize(writer, value); string output = sw.ToString(); writer.Close(); sw.Close(); return output; } public object Deserialize(string jsonText, Type valueType) { Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer(); json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace; json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore; json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; StringReader sr = new StringReader(jsonText); Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr); object result = json.Deserialize(reader, valueType); reader.Close(); return result; } } }
调用页面前台
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UltraWebGridJSON.aspx.cs" Inherits="Web.UltraWebGridJSON" %> <%@ Register Assembly="Infragistics35.WebUI.UltraWebGrid.v8.3, Version=8.3.20083.1009, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb" Namespace="Infragistics.WebUI.UltraWebGrid" TagPrefix="igtbl" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <mce:script src="Scripts/jquery-1.2.6.min.js" mce_src="Scripts/jquery-1.2.6.min.js" type="text/javascript"></mce:script> <mce:script type="text/javascript"><!-- $(function() { var grid = igtbl_getGridById("Grid"); $.getJSON("UltraWebGridJSON.aspx?Json=json", function(data) { $.each(data.Rows, function(i, n) { igtbl_addNew("Grid", 0); grid.Rows.getRow(i).getCellFromKey("title").setValue(n.title); grid.Rows.getRow(i).getCellFromKey("filename").setValue(n.filename); grid.Rows.getRow(i).getCellFromKey("sortorder").setValue(n.sortorder); }); grid.Rows.getRow(0).scrollToView(); }) }) // --></mce:script> <mce:script type="text/javascript" id="igClientScript"><!-- function Grid_InitializeLayoutHandler(gridName) { //Add code to handle your event here. } // --></mce:script> </head> <body> <form id="form1" runat="server"> <div id="ddlDiv"> <igtbl:UltraWebGrid ID="Grid" runat="server" Height="200px" Width="100%"> <Bands> <igtbl:UltraGridBand> <RowTemplateStyle BackColor="Window" BorderColor="Window" BorderStyle="Ridge"> <BorderDetails WidthBottom="3px" WidthLeft="3px" WidthRight="3px" WidthTop="3px" /> </RowTemplateStyle> <Columns> <igtbl:UltraGridColumn BaseColumnName="title" Key="title"> <Header> <RowLayoutColumnInfo OriginX="2" /> </Header> <Footer> <RowLayoutColumnInfo OriginX="2" /> </Footer> </igtbl:UltraGridColumn> <igtbl:UltraGridColumn BaseColumnName="filename" Key="filename"> <Header> <RowLayoutColumnInfo OriginX="4" /> </Header> <Footer> <RowLayoutColumnInfo OriginX="4" /> </Footer> </igtbl:UltraGridColumn> <igtbl:UltraGridColumn BaseColumnName="sortorder" Key="sortorder"> <Header> <RowLayoutColumnInfo OriginX="5" /> </Header> <Footer> <RowLayoutColumnInfo OriginX="5" /> </Footer> </igtbl:UltraGridColumn> </Columns> <AddNewRow View="NotSet" Visible="NotSet"> </AddNewRow> </igtbl:UltraGridBand> </Bands> <DisplayLayout AllowColSizingDefault="Free" AllowAddNewDefault="Yes" AllowColumnMovingDefault="OnServer" AllowDeleteDefault="Yes" AllowSortingDefault="OnClient" AllowUpdateDefault="Yes" BorderCollapseDefault="Separate" HeaderClickActionDefault="SortMulti" Name="UltraWebGrid1" RowHeightDefault="20px" RowSelectorsDefault="No" SelectTypeRowDefault="Extended" StationaryMargins="Header" StationaryMarginsOutlookGroupBy="True" TableLayout="Fixed" Version="4.00" ViewType="OutlookGroupBy" AutoGenerateColumns="False"> <FrameStyle BackColor="Window" BorderColor="InactiveCaption" BorderStyle="Solid" BorderWidth="1px" Font-Names="Microsoft Sans Serif" Font-Size="8.25pt" Height="200px" Width="100%"> </FrameStyle> <ClientSideEvents InitializeLayoutHandler="Grid_InitializeLayoutHandler" /> <Pager MinimumPagesForDisplay="2"> <PagerStyle BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px"> <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" /> </PagerStyle> </Pager> <EditCellStyleDefault BorderStyle="None" BorderWidth="0px"> </EditCellStyleDefault> <FooterStyleDefault BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Left" VerticalAlign="Middle" Wrap="True"> <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" /> </FooterStyleDefault> <HeaderStyleDefault BackColor="LightGray" BorderStyle="Solid" HorizontalAlign="Left"> <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" /> </HeaderStyleDefault> <RowStyleDefault BackColor="Window" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" Font-Names="Microsoft Sans Serif" Font-Size="8.25pt"> <Padding Left="3px" /> <BorderDetails ColorLeft="Window" ColorTop="Window" /> </RowStyleDefault> <GroupByRowStyleDefault BackColor="Control" BorderColor="Window"> </GroupByRowStyleDefault> <GroupByBox> <BoxStyle BackColor="ActiveBorder" BorderColor="Window"> </BoxStyle> </GroupByBox> <AddNewBox Hidden="True"> <BoxStyle BackColor="Window" BorderColor="InactiveCaption" BorderStyle="Solid" BorderWidth="1px"> <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" /> </BoxStyle> </AddNewBox> <ActivationObject BorderColor="" BorderWidth=""> </ActivationObject> <FilterOptionsDefault> <FilterDropDownStyle BackColor="White" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CustomRules="overflow:auto;" Font-Names="Verdana,Arial,Helvetica,sans-serif" Font-Size="11px" Height="300px" Width="200px"> <Padding Left="2px" /> </FilterDropDownStyle> <FilterHighlightRowStyle BackColor="#151C55" ForeColor="White"> </FilterHighlightRowStyle> <FilterOperandDropDownStyle BackColor="White" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px" CustomRules="overflow:auto;" Font-Names="Verdana,Arial,Helvetica,sans-serif" Font-Size="11px"> <Padding Left="2px" /> </FilterOperandDropDownStyle> </FilterOptionsDefault> </DisplayLayout> </igtbl:UltraWebGrid> </div> </form> </body> </html>
调用页面后台
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.Practices.EnterpriseLibrary.Data; using Utility; using Newtonsoft.Json; namespace Web { public partial class UltraWebGridJSON : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(Request.QueryString["Json"]=="json") { var sql = @"select id, title,title as test, filename, sortorder, createtime, filesize, width, height, classid from t_dataview order by sortorder"; Database db = DatabaseFactory.CreateDatabase(); var dt = db.ExecuteDataSet(CommandType.Text, sql).Tables[0]; Serialize sel = new Serialize(); var selStr = sel.Serializer(dt); Response.Clear(); Response.Write(selStr); Response.Flush(); Response.End(); } if (!IsPostBack) { } } } }
igtbl_addNew("Grid", 0, false, true); 这个函数解释一下,根据API上面说的,第三个参数是加行的时候,滚动条是否跑到新加的到行
这里设成false了,所以加的时候不会跟着动,第四个参数就是是否把加的那行设为活动行(set the newly added row as the active row for the grid)