加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

ASP.NET,C#和匿名类型 – 在手动构建匿名类型时迭代DataTable

发布时间:2020-12-16 03:51:04 所属栏目:asp.Net 来源:网络整理
导读:我目前正在使用ASP.NET,jQuery和 JSON实现客户端分页解决方案. 我一直在关注来自encosia的优秀文章:http://encosia.com/2008/08/20/easily-build-powerful-client-side-ajax-paging-using-jquery/ 在我的Web方法中,我将数据从数据库中检索为DataTable: Dat
我目前正在使用ASP.NET,jQuery和 JSON实现客户端分页解决方案.

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

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

DataTable categoryProducts = ProductViewerAccess.GetCategoryProducts
        ("AA",4,Page.ToString(),out howManyPages,"FALSE","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)和其他预处理(例如,调用各种函数来构建基于图像ID的图像URL – 在将DataTable的结果行作为匿名类型返回给客户端之前,这是DataTable中未显示在代码片段中的另一列.

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

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

亲切的问候

沃尔特

解决方法

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

var feeds =
    from feed in categoryProducts.AsEnumerable()
    select new
    {
        Description = feed.Field<string>("description"),// 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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读