c# - ASP.NET、C# 和匿名类型 - 在手动构建匿名类型时迭代数据表

标签 c# asp.net anonymous-types

我目前正在使用 ASP.NET、jQuery 和 JSON 实现客户端分页解决方案。

我一直在关注来自 encosia 的优秀文章:http://encosia.com/2008/08/20/easily-build-powerful-client-side-ajax-paging-using-jquery/

在我的 Web 方法中,我从数据库中检索数据作为数据表:

    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>

关于c# - ASP.NET、C# 和匿名类型 - 在手动构建匿名类型时迭代数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2089722/

相关文章:

c# - 如何访问匿名linq对象的已定义属性?

c# - 获取对象类的类型、属性和值

.net - 为 Visual Studio 安装 Razor View 引擎

c# - 尝试确定两个 List<T> 中的公共(public)元素时出现问题

c# - 如何通过显示文本在 ASP.NET 下拉列表中设置所选项目?

ASP.NET 在请求期间存储上下文数据

c# - Distinct() 如何处理匿名类型的 List<>?

delphi - delphi 中的匿名记录构造函数

c# - 在紧凑型和完整 .net 框架之间切换编译?

c# - 如何使用 Orchard CMS 创建推荐页面?