ASP.NET,C#和匿名类型 - 在手动构建匿名类型时遍历数据表

问题描述:

我目前正在使用ASP.NET,jQuery和JSON实现客户端分页解决方案。ASP.NET,C#和匿名类型 - 在手动构建匿名类型时遍历数据表

我一直跟着从encosia的优秀文章:http://encosia.com/2008/08/20/easily-build-powerful-client-side-ajax-paging-using-jquery/

在我的Web方法我从数据库中检索我的数据作为一个DataTable:

DataTable categoryProducts = ProductViewerAccess.GetCategoryProducts 
     ("AA", 4, 0, Page.ToString(), out howManyPages, "FALSE", 0, "CostPrice", "asc", destinationList); 

我然后检索DataTable中的数据转换成匿名类型:

var feeds = 
     from feed in categoryProducts.AsEnumerable() 
     select new 
     { 
      Description = feed.Field<string>("description"), 
      MfPartNo = feed.Field<string>("MfPN"), 
      Inventory = feed.Field<Int32>("Inventory") 
     }; 

匿名类型,然后从Web方法在客户端返回:

return feeds.Take(PageSize);

模板然后提取和显示领域:

<tbody> 
    {#foreach $T.d as post} 
    <tr> 
     <td> 
     {$T.post.Description} 
     <p>Mfr#: {$T.post.MfPartNo}</p> 
     </td> 
     <td>{$T.post.Inventory}</td> 
    </tr> 
    {#/for} 
    </tbody> 

这一切的伟大工程。但是,我想扩展代码以执行一些评估检查(例如,检查DataTable中的各列不是NULL)和其他预处理(例如,调用各种函数来构建基于在DataTable的结果行作为匿名类型返回给客户端之前,图像ID(DataTable中的另一列未在代码片段中显示))。

基本上,我想遍历DataTable,执行评估检查和预处理,同时手动构建我的匿名类型。或者也许有更好的方法来实现这一目标?

无论如何我能做到这一点吗?

亲切的问候

沃尔特

我认为检查空值可能是在服务器端有意义的东西。道格拉斯描述的方法是可行的。另一个是处理你正在构建匿名类型的集合空问题:

var feeds = 
    from feed in categoryProducts.AsEnumerable() 
    select new 
    { 
     Description = feed.Field<string>("description"), 
     MfPartNo = feed.Field<string>("MfPN"), 
     // Return 0 if the inventory value is null. 
     Inventory = (int?)feed.Field("Inventory") ?? 0 
    }; 

ScottGu对using the null coalescing operator to handle nulls concisely好的帖子,如上图所示。

至于建立链接,这是我可能会建议在客户端模板中做的事情。这样可以消除以JSON方式发送的相当多的冗余数据。像这样的东西,例如:

<tbody> 
    {#foreach $T.d as post} 
    <tr> 
    <td> 
     <a href="/url/to/details.aspx?id={$T.post.ID}">{$T.post.Description}</a> 
     <p>Mfr#: {$T.post.MfPartNo}</p> 
    </td> 
    <td>{$T.post.Inventory}</td> 
    </tr> 
    {#/for} 
</tbody> 

有时候,我发现它有助于使用LINQ to储值我需要在随后的查询中使用使用“让”的关键字。稍后我可以使用这个变量来进行简单的空检查或其他事情。例如:

var feeds = 
    from feed in categoryProducts.AsEnumerable() 
    let MfPN = feed.Field<string>("MfPN") 
    // Get image url if MfPN is not null, else return default image url. 
    let Url = !string.IsNullOrEmpty(MfPN) ? GetImgUrl(MfPN) : “DefaultImage.jpg” 
     select new 
     { 
      Description = feed.Field<string>("description"), 
      MfPartNo = MfPN, 
      Inventory = feed.Field<Int32>("Inventory"), 
      ImageUrl = Url 
     }; 

我能想到的,如果过于简单调用LINQ查询之前在数据表执行的预处理唯一的其他东西。

希望这会有所帮助。