A DataTable Serializer for ASP.NET AJAX(转载)

此文转载自http://www.dennydotnet.com/post/2007/09/A-DataTable-Serializer-for-ASPNET-AJAX.aspx,未作翻译。

A DataTable Serializer for ASP.NET AJAX, implements JavaScriptConverter. Note that I did not implement a Deserialize method since I am using this for read only data.

[code:c#]
/// <summary>
/// DataTable to JSON converter
/// </summary>

public class JavaScriptDataTableConverter : JavaScriptConverter {
 
public override object Deserialize( IDictionary<stringobject> dictionary, Type type, JavaScriptSerializer serializer ) {
  
throw new NotImplementedException( "Deserialize is not implemented." );
 }
 

 
public override IDictionary<stringobject> Serialize( object obj, JavaScriptSerializer serializer ) {
  DataTable dt 
= obj as DataTable;
  Dictionary
<stringobject> result = new Dictionary<stringobject>(); 

  
if( dt != null && dt.Rows.Count > 0 ) {
   
// List for row values
   List<object> rowValues = new List<object>(); 

   
foreach( DataRow dr in dt.Rows ) {
    
// Dictionary for col name / col value
    Dictionary<stringobject> colValues = new Dictionary<stringobject>(); 

    
foreach( DataColumn dc in dt.Columns ) {
     colValues.Add( dc.ColumnName, 
// col name
      ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
    }
 

    
// Add values to row
    rowValues.Add( colValues );
   }
 

   
// Add rows to serialized object
   result["rows"= rowValues;
  }
 

  
return result;
 }
 

 
public override IEnumerable<Type> SupportedTypes {
  
//Define the DataTable as a supported type.
  get {
   
return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
    
new List<Type>(
     
new Type[] typeof( DataTable ) }
    )
   );
  }

 }

}



[/code]

 

And how do you implement this? In a web service...

[code:c#]
using System.Web.Script.Serialization; 

//  

[WebMethod()]
[ScriptMethod( ResponseFormat 
= ResponseFormat.Json )]
public string TestJS( int Id ) {
 JavaScriptSerializer toJSON 
= new JavaScriptSerializer();
 toJSON.RegisterConverters( 
new JavaScriptConverter[] new JavaScriptDataTableConverter() } ); 

 DataTable dt 
= new Query( Log.Schema )
   .WHERE( Log.Columns.ID, Id )
   .ExecuteDataSet().Tables[
0]; 

 
return toJSON.Serialize( dt );
}


[/code]

 

That's all there is to it! Just deserialize to an object on the client-side and you're good to go!

Side Note: There is a DataTable serializer from Microsoft in the ASP.NET Futures package.

posted on 2007-11-22 12:19 客家网络 阅读(209) 评论(0)  编辑 收藏 网摘 所属分类: .NET2.0技术




发表评论

昵称: [登录] [注册]

主页:

邮箱:(仅博主可见)

评论内容:

  登录  注册

[使用Ctrl+Enter键快速提交评论]

0 968390




相关文章:

相关链接:

导航

公告

发布“图片水印工具”beta版本,欢迎使用,并提出意见与建议。
看 三国演义 到刘备夺取西川
<2007年11月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

统计

与我联系

搜索

 

常用链接

留言簿

我参加的小组

我的标签

随笔分类(12)

随笔档案(14)

最新评论

阅读排行榜

评论排行榜