asp.net-mvc-3 - 如何在 ASP.NET Razor 表中编写汇总行代码?

标签 asp.net-mvc-3 linq entity-framework razor

我在 Razor View 中构建了一个表格,如下所示:

@foreach (var item in Model)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.column1)</td>
        ...
        ...
    </tr>
}

我想在最后添加表格摘要,例如:

<tr>
    <td>@Model.Sum(a => a.column1)</td>
    ...
    ...
</tr>

这实际上有效,但它没有使用我的数据注释,因为我没有使用 DisplayFor()。我尝试将 Model.Sum 放在 DisplayFor() 中,但代码不起作用。谁能指出我的解决方案吗?

最佳答案

您可以编写一个 HTML 帮助程序来检查属性 lambda、执行 sum() 并利用您的数据注释。

查看模型

public class FooViewModel
{
    [Required]
    [Display( Name = "My Display Name" )]
    public int Bar {
        get;
        set;
    }

    public string Baz {
        get;
        set;
    }
}

查看

@model IEnumerable<FooViewModel>

@* Razor engine prefers this syntax? think generic may confuse it *@
@(Html.SumFor<FooViewModel>( o => o.Bar ))

帮助扩展

这远非完美。一项改进是允许对任何类型进行求和,而不必为每个可求和类型提供不同的方法。

public static IHtmlString SumFor<TEnumerableItem>( this HtmlHelper helper, 
    Expression<Func<TEnumerableItem, int>> expression ) {

    // get metadata through slightly convoluted means since the model
    // is actually a collection of the type we want to know about

    // lambda examination
    var propertyName = ( (MemberExpression)expression.Body ).Member.Name;

    // property metadata retrieval
    var metadata = ModelMetadataProviders.Current
        .GetMetadataForProperty( null, typeof( TEnumerableItem ), propertyName );

    // make an assumption about the parent model (would be better to enforce 
    // this with a generic constraint somehow)
    var ienum = (IEnumerable<TEnumerableItem>)helper.ViewData.Model;

    // get func from expression
    var f = expression.Compile();

    // perform op
    var sum = ienum.Sum( f );

    // all model metadata is available here for the property and the parent type
    return MvcHtmlString.Create( 
       string.Format( "<div>Sum of {0} is {1}.</div>", metadata.DisplayName, sum )
    );
}

关于asp.net-mvc-3 - 如何在 ASP.NET Razor 表中编写汇总行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12326381/

相关文章:

c# - LINQ 连接查询返回匹配的记录

c# LINQ Take 用于内部查询

c# - O365 通过 ASP.NET MVC 中的 PowerShell 3 : MicrosoftOnlineException was thrown

facebook - DotNetOpenAuth 声称来自 Facebook 的标识符永远不会相同

asp.net-mvc - MVC 页面在第一次查看时变慢

asp.net-mvc - 如何将文件上传到服务器硬盘。使用MVC

c# - 如何将 Action 提取到成员函数中?

c# - 是否有任何预先存在的可枚举扩展使其 NullReferenceException 安全?

c# - 在 mvc ef 中动态选择显示名称的两个标签

c# - 更新应用程序后 ASP.NET MVC 停止工作 - MembershipUser 出现问题