How to compose a summary row in a Razor ASP.NET table?

I have a table built in a Razor view that looks like this:

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

I want to add a table summary at the end, something like:

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

This really works, but it does not use my data annotations since I do not use DisplayFor (). I tried to place Model.Sum in DisplayFor (), but the code does not work. Can someone point me to a solution?

+5
source share
3 answers

You can write an HTML helper that examined the lambda property, executed sum (), and used your data annotations.

View Model

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

    public string Baz {
        get;
        set;
    }
}

View

@model IEnumerable<FooViewModel>

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

Helper extension

. , .

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 )
    );
}
+3

, ... DataAnnotation:

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

displayfor .

0

jQuery Datatables. Javasript "" , / . , - , , - - " 1 8 "

0

All Articles