• Newtonsoft.Json 为asp.net 3.5开发的


    使用的库是: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

    C-sharp代码 复制代码
    1. using System;   
    2.  using System.Collections.Generic;   
    3.  using System.Data;   
    4.  using System.Linq;   
    5.  using System.Text;   
    6.  using Newtonsoft.Json;   
    7.  namespace Utility   
    8. {   
    9.     public class DataRowConverter : JsonConverter   
    10.     {   
    11.         /// <summary>   
    12.         /// Writes the JSON representation of the object.   
    13.         /// </summary>   
    14.         /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>   
    15.         /// <param name="value">The value.</param>   
    16.         public override void WriteJson(JsonWriter writer, object dataRow, JsonSerializer serializer)   
    17.         {   
    18.             DataRow row = dataRow as DataRow;   
    19.             // *** HACK: need to use root serializer to write the column value   
    20.             //     should be fixed in next ver of JSON.NET with writer.Serialize(object)   
    21.             JsonSerializer ser = new JsonSerializer();   
    22.             writer.WriteStartObject();   
    23.             foreach (DataColumn column in row.Table.Columns)   
    24.             {   
    25.                 writer.WritePropertyName(column.ColumnName);   
    26.                 ser.Serialize(writer, row[column]);   
    27.             }   
    28.             writer.WriteEndObject();   
    29.         }   
    30.         /// <summary>   
    31.         /// Determines whether this instance can convert the specified value type.   
    32.         /// </summary>   
    33.         /// <param name="valueType">Type of the value.</param>   
    34.         /// <returns>   
    35.         ///     <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.   
    36.         /// </returns>   
    37.         public override bool CanConvert(Type valueType)   
    38.         {   
    39.             return typeof(DataRow).IsAssignableFrom(valueType);   
    40.         }   
    41.         /// <summary>   
    42.         /// Reads the JSON representation of the object.   
    43.         /// </summary>   
    44.         /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>   
    45.         /// <param name="objectType">Type of the object.</param>   
    46.         /// <returns>The object value.</returns>   
    47.         public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)   
    48.         {   
    49.             throw new NotImplementedException();   
    50.         }   
    51.     }   
    52. }  

    DataSetConverter .cs

    C-sharp代码 复制代码
    1. using System;   
    2.  using System.Collections.Generic;   
    3.  using System.Data;   
    4.  using System.Linq;   
    5.  using System.Reflection;   
    6.  using System.Text;   
    7.  using Newtonsoft.Json;   
    8. namespace Utility   
    9. {   
    10.     public class DataSetConverter : JsonConverter   
    11.     {   
    12.         /// <summary>   
    13.         /// Writes the JSON representation of the object.   
    14.         /// </summary>   
    15.         /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>   
    16.         /// <param name="value">The value.</param>   
    17.         public override void WriteJson(JsonWriter writer, object dataset, JsonSerializer serializer)   
    18.         {   
    19.             DataSet dataSet = dataset as DataSet;   
    20.             DataTableConverter converter = new DataTableConverter();   
    21.             writer.WriteStartObject();   
    22.             writer.WritePropertyName("Tables");   
    23.             writer.WriteStartArray();   
    24.             BindingFlags bf = BindingFlags.Public | BindingFlags.Static;   
    25.             foreach (DataTable table in dataSet.Tables)   
    26.             {   
    27.                 converter.WriteJson(writer, table, serializer);   
    28.             }   
    29.             writer.WriteEndArray();   
    30.             writer.WriteEndObject();   
    31.         }   
    32.         /// <summary>   
    33.         /// Determines whether this instance can convert the specified value type.   
    34.         /// </summary>   
    35.         /// <param name="valueType">Type of the value.</param>   
    36.         /// <returns>   
    37.         ///     <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.   
    38.         /// </returns>   
    39.         public override bool CanConvert(Type valueType)   
    40.         {   
    41.             return typeof(DataSet).IsAssignableFrom(valueType);   
    42.         }   
    43.         /// <summary>   
    44.         /// Reads the JSON representation of the object.   
    45.         /// </summary>   
    46.         /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>   
    47.         /// <param name="objectType">Type of the object.</param>   
    48.         /// <returns>The object value.</returns>   
    49.         public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)   
    50.         {   
    51.             throw new NotImplementedException();   
    52.         }   
    53.     }   
    54. }  

    DataTableConverter.cs

    C-sharp代码 复制代码
    1. using System;   
    2. using System.Collections.Generic;   
    3. using System.Data;   
    4. using System.Linq;   
    5. using System.Text;   
    6. using Newtonsoft.Json;   
    7. namespace Utility   
    8. {   
    9.     public class DataTableConverter : JsonConverter   
    10.     {   
    11.         /// <summary>   
    12.         /// Writes the JSON representation of the object.   
    13.         /// </summary>   
    14.         /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>   
    15.         /// <param name="value">The value.</param>   
    16.         public override void WriteJson(JsonWriter writer, object dataTable, JsonSerializer serializer)   
    17.         {   
    18.             DataTable table = dataTable as DataTable;   
    19.             DataRowConverter converter = new DataRowConverter();   
    20.             writer.WriteStartObject();   
    21.             writer.WritePropertyName("Rows");   
    22.             writer.WriteStartArray();   
    23.             foreach (DataRow row in table.Rows)   
    24.             {   
    25.                 converter.WriteJson(writer, row,serializer);   
    26.             }   
    27.             writer.WriteEndArray();   
    28.             writer.WriteEndObject();   
    29.         }   
    30.         /// <summary>   
    31.         /// Determines whether this instance can convert the specified value type.   
    32.         /// </summary>   
    33.         /// <param name="valueType">Type of the value.</param>   
    34.         /// <returns>   
    35.         ///     <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.   
    36.         /// </returns>   
    37.         public override bool CanConvert(Type valueType)   
    38.         {   
    39.             return typeof(DataTable).IsAssignableFrom(valueType);   
    40.         }   
    41.         /// <summary>   
    42.         /// Reads the JSON representation of the object.   
    43.         /// </summary>   
    44.         /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>   
    45.         /// <param name="objectType">Type of the object.</param>   
    46.         /// <returns>The object value.</returns>   
    47.         public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)   
    48.         {   
    49.             throw new NotImplementedException();   
    50.         }   
    51.     }   
    52. }  

    Serialize.cs

    C-sharp代码 复制代码
    1. using System;   
    2. using System.Collections.Generic;   
    3. using System.Data;   
    4. using System.IO;   
    5. using System.Linq;   
    6. using System.Text;   
    7. using Newtonsoft.Json;   
    8. namespace Utility   
    9. {   
    10.     public class Serialize   
    11.     {   
    12.         public string Serializer(object value)   
    13.         {   
    14.             Type type = value.GetType();   
    15.             Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();   
    16.             json.NullValueHandling = NullValueHandling.Ignore;   
    17.             json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;   
    18.             json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;   
    19.             json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;   
    20.             if (type == typeof(DataRow))   
    21.                 json.Converters.Add(new DataRowConverter());   
    22.             else if (type == typeof(DataTable))   
    23.                 json.Converters.Add(new DataTableConverter());   
    24.             else if (type == typeof(DataSet))   
    25.                 json.Converters.Add(new DataSetConverter());   
    26.             StringWriter sw = new StringWriter();   
    27.             Newtonsoft.Json.JsonTextWriter writer = new JsonTextWriter(sw);   
    28.             writer.Formatting = Formatting.Indented;   
    29.             writer.QuoteChar = '"';   
    30.             json.Serialize(writer, value);   
    31.             string output = sw.ToString();   
    32.             writer.Close();   
    33.             sw.Close();   
    34.             return output;   
    35.         }   
    36.         public object Deserialize(string jsonText, Type valueType)   
    37.         {   
    38.             Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();   
    39.             json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;   
    40.             json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;   
    41.             json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;   
    42.             json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;   
    43.             StringReader sr = new StringReader(jsonText);   
    44.             Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);   
    45.             object result = json.Deserialize(reader, valueType);   
    46.             reader.Close();   
    47.             return result;   
    48.         }   
    49.     }   
    50. }  

    调用页面前台

    Xhtml代码 复制代码
    1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UltraWebGridJSON.aspx.cs"  
    2.     Inherits="Web.UltraWebGridJSON" %>  
    3. <%@ Register Assembly="Infragistics35.WebUI.UltraWebGrid.v8.3, Version=8.3.20083.1009, Culture=neutral, PublicKeyToken=7dd5c3163f2cd0cb"  
    4.     Namespace="Infragistics.WebUI.UltraWebGrid" TagPrefix="igtbl" %>  
    5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    6. <html xmlns="http://www.w3.org/1999/xhtml">  
    7. <head runat="server">  
    8.     <title></title>  
    9.     <mce:script src="Scripts/jquery-1.2.6.min.js" mce_src="Scripts/jquery-1.2.6.min.js" type="text/javascript"></mce:script>  
    10.     <mce:script type="text/javascript"><!--   
    11.         $(function() {   
    12.             var grid = igtbl_getGridById("Grid");   
    13.             $.getJSON("UltraWebGridJSON.aspx?Json=json", function(data) {   
    14.                 $.each(data.Rows, function(i, n) {   
    15.                     igtbl_addNew("Grid", 0);   
    16.                     grid.Rows.getRow(i).getCellFromKey("title").setValue(n.title);   
    17.                     grid.Rows.getRow(i).getCellFromKey("filename").setValue(n.filename);   
    18.                     grid.Rows.getRow(i).getCellFromKey("sortorder").setValue(n.sortorder);   
    19.                 });   
    20.                 grid.Rows.getRow(0).scrollToView();   
    21.             })   
    22.         })   
    23.        
    24. // --></mce:script>  
    25.     <mce:script type="text/javascript" id="igClientScript"><!--   
    26.         function Grid_InitializeLayoutHandler(gridName) {   
    27.             //Add code to handle your event here.   
    28.         }   
    29. // --></mce:script>  
    30. </head>  
    31. <body>  
    32.     <form id="form1" runat="server">  
    33.     <div id="ddlDiv">  
    34.         <igtbl:UltraWebGrid ID="Grid" runat="server" Height="200px" Width="100%">  
    35.             <Bands>  
    36.                 <igtbl:UltraGridBand>  
    37.                     <RowTemplateStyle BackColor="Window" BorderColor="Window" BorderStyle="Ridge">  
    38.                         <BorderDetails WidthBottom="3px" WidthLeft="3px" WidthRight="3px" WidthTop="3px" />  
    39.                     </RowTemplateStyle>  
    40.                     <Columns>  
    41.                         <igtbl:UltraGridColumn BaseColumnName="title" Key="title">  
    42.                             <Header>  
    43.                                 <RowLayoutColumnInfo OriginX="2" />  
    44.                             </Header>  
    45.                             <Footer>  
    46.                                 <RowLayoutColumnInfo OriginX="2" />  
    47.                             </Footer>  
    48.                         </igtbl:UltraGridColumn>  
    49.                         <igtbl:UltraGridColumn BaseColumnName="filename" Key="filename">  
    50.                             <Header>  
    51.                                 <RowLayoutColumnInfo OriginX="4" />  
    52.                             </Header>  
    53.                             <Footer>  
    54.                                 <RowLayoutColumnInfo OriginX="4" />  
    55.                             </Footer>  
    56.                         </igtbl:UltraGridColumn>  
    57.                         <igtbl:UltraGridColumn BaseColumnName="sortorder" Key="sortorder">  
    58.                             <Header>  
    59.                                 <RowLayoutColumnInfo OriginX="5" />  
    60.                             </Header>  
    61.                             <Footer>  
    62.                                 <RowLayoutColumnInfo OriginX="5" />  
    63.                             </Footer>  
    64.                         </igtbl:UltraGridColumn>  
    65.                     </Columns>  
    66.                     <AddNewRow View="NotSet" Visible="NotSet">  
    67.                     </AddNewRow>  
    68.                 </igtbl:UltraGridBand>  
    69.             </Bands>  
    70.             <DisplayLayout AllowColSizingDefault="Free" AllowAddNewDefault="Yes" AllowColumnMovingDefault="OnServer"  
    71.                 AllowDeleteDefault="Yes" AllowSortingDefault="OnClient" AllowUpdateDefault="Yes"  
    72.                 BorderCollapseDefault="Separate" HeaderClickActionDefault="SortMulti" Name="UltraWebGrid1"  
    73.                 RowHeightDefault="20px" RowSelectorsDefault="No" SelectTypeRowDefault="Extended"  
    74.                 StationaryMargins="Header" StationaryMarginsOutlookGroupBy="True" TableLayout="Fixed"  
    75.                 Version="4.00" ViewType="OutlookGroupBy" AutoGenerateColumns="False">  
    76.                 <FrameStyle BackColor="Window" BorderColor="InactiveCaption" BorderStyle="Solid"  
    77.                     BorderWidth="1px" Font-Names="Microsoft Sans Serif" Font-Size="8.25pt" Height="200px"  
    78.                     Width="100%">  
    79.                 </FrameStyle>  
    80.                 <ClientSideEvents InitializeLayoutHandler="Grid_InitializeLayoutHandler" />  
    81.                 <Pager MinimumPagesForDisplay="2">  
    82.                     <PagerStyle BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px">  
    83.                         <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />  
    84.                     </PagerStyle>  
    85.                 </Pager>  
    86.                 <EditCellStyleDefault BorderStyle="None" BorderWidth="0px">  
    87.                 </EditCellStyleDefault>  
    88.                 <FooterStyleDefault BackColor="LightGray" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Left"  
    89.                     VerticalAlign="Middle" Wrap="True">  
    90.                     <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />  
    91.                 </FooterStyleDefault>  
    92.                 <HeaderStyleDefault BackColor="LightGray" BorderStyle="Solid" HorizontalAlign="Left">  
    93.                     <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />  
    94.                 </HeaderStyleDefault>  
    95.                 <RowStyleDefault BackColor="Window" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px"  
    96.                     Font-Names="Microsoft Sans Serif" Font-Size="8.25pt">  
    97.                     <Padding Left="3px" />  
    98.                     <BorderDetails ColorLeft="Window" ColorTop="Window" />  
    99.                 </RowStyleDefault>  
    100.                 <GroupByRowStyleDefault BackColor="Control" BorderColor="Window">  
    101.                 </GroupByRowStyleDefault>  
    102.                 <GroupByBox>  
    103.                     <BoxStyle BackColor="ActiveBorder" BorderColor="Window">  
    104.                     </BoxStyle>  
    105.                 </GroupByBox>  
    106.                 <AddNewBox Hidden="True">  
    107.                     <BoxStyle BackColor="Window" BorderColor="InactiveCaption" BorderStyle="Solid" BorderWidth="1px">  
    108.                         <BorderDetails ColorLeft="White" ColorTop="White" WidthLeft="1px" WidthTop="1px" />  
    109.                     </BoxStyle>  
    110.                 </AddNewBox>  
    111.                 <ActivationObject BorderColor="" BorderWidth="">  
    112.                 </ActivationObject>  
    113.                 <FilterOptionsDefault>  
    114.                     <FilterDropDownStyle BackColor="White" BorderColor="Silver" BorderStyle="Solid" BorderWidth="1px"  
    115.                         CustomRules="overflow:auto;" Font-Names="Verdana,Arial,Helvetica,sans-serif"  
    116.                         Font-Size="11px" Height="300px" Width="200px">  
    117.                         <Padding Left="2px" />  
    118.                     </FilterDropDownStyle>  
    119.                     <FilterHighlightRowStyle BackColor="#151C55" ForeColor="White">  
    120.                     </FilterHighlightRowStyle>  
    121.                     <FilterOperandDropDownStyle BackColor="White" BorderColor="Silver" BorderStyle="Solid"  
    122.                         BorderWidth="1px" CustomRules="overflow:auto;" Font-Names="Verdana,Arial,Helvetica,sans-serif"  
    123.                         Font-Size="11px">  
    124.                         <Padding Left="2px" />  
    125.                     </FilterOperandDropDownStyle>  
    126.                 </FilterOptionsDefault>  
    127.             </DisplayLayout>  
    128.         </igtbl:UltraWebGrid>  
    129.     </div>  
    130.     </form>  
    131. </body>  
    132. </html>  

    调用页面后台

    C-sharp代码 复制代码
    1. using System;   
    2. using System.Collections.Generic;   
    3. using System.Data;   
    4. using System.IO;   
    5. using System.Linq;   
    6. using System.Text;   
    7. using System.Web;   
    8. using System.Web.UI;   
    9. using System.Web.UI.WebControls;   
    10. using Microsoft.Practices.EnterpriseLibrary.Data;   
    11. using Utility;   
    12. using Newtonsoft.Json;   
    13. namespace Web   
    14. {   
    15.     public partial class UltraWebGridJSON : System.Web.UI.Page   
    16.     {   
    17.         protected void Page_Load(object sender, EventArgs e)   
    18.         {   
    19.             if(Request.QueryString["Json"]=="json")   
    20.             {   
    21.                 var sql =   
    22. @"select id, title,title as test, filename, sortorder,    
    23.         createtime, filesize, width, height, classid   
    24.             from t_dataview order by sortorder";   
    25.                 Database db = DatabaseFactory.CreateDatabase();   
    26.                 var dt = db.ExecuteDataSet(CommandType.Text,   
    27.                                            sql).Tables[0];   
    28.                 Serialize sel = new Serialize();   
    29.                 var selStr = sel.Serializer(dt);   
    30.                 Response.Clear();   
    31.                 Response.Write(selStr);   
    32.                 Response.Flush();   
    33.                 Response.End();   
    34.             }   
    35.             if (!IsPostBack)   
    36.             {   
    37.             }   
    38.         }   
    39.     }   
    40. }  

    igtbl_addNew("Grid", 0, false, true); 这个函数解释一下,根据API上面说的,第三个参数是加行的时候,滚动条是否跑到新加的到行

    这里设成false了,所以加的时候不会跟着动,第四个参数就是是否把加的那行设为活动行(set the newly added row as the active row for the grid)

  • 相关阅读:
    【转】ArcGIS 合并要素 Union Dissolve Append Merge
    Linux命令行下编辑常用快捷键
    rpm aid用法
    SUSE 吉祥物图片
    F9初装体验
    openSUSE10、SUSE EVAL10和SUSE10的区别[翻译]
    装有Linux DIY牛人百元人民币昂贵甜头液晶一体机
    SUSE10.3恢复GRUB体例
    64位Fedora还挑CPU
    Ubuntu8.04安置XCrysDen
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/1997349.html
Copyright © 2020-2023  润新知