如何在ASP.NET Razor表中编写汇总行?

时间:2012-09-07 22:47:39

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

我有一个在Razor视图中构建的表,如下所示:

@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()中,但代码不起作用。有人能指出我的解决方案吗?

3 个答案:

答案 0 :(得分:3)

您可以编写一个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 )
    );
}

答案 1 :(得分:0)

我希望我理解你...在你的模型中添加一个属性并使用你需要的DataAnnotation:

    [MyDataAnnotation]
    public int Sum
    {
        get
        {
            var sum = 0;
            foreach(var item in this)
            {
                sum += item.Value;
            }    
            return sum;     
        }
    }

然后使用带有此属性的displayfor。

答案 2 :(得分:0)

您可以使用jQuery Datatables插件。在Javasript中,您只需打开/关闭表配置属性即可获得大量“免费赠品”。因此,您可以在表格顶部找到一个搜索框 - 按字母顺序自动排序列,例如您还可以在表格底部获得一个信息行 - 例如“显示8个条目中的1个”