5

私は次のように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()内に配置しようとしましたが、コードが機能しません。誰かが私を解決策に向けることができますか?

4

3 に答える 3

3

プロパティlambdaを調べ、sum()を実行し、データアノテーションを利用するHTMLヘルパーを作成できます。

モデルを表示

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 )
    );
}
于 2012-09-07T22:53:55.603 に答える
1

私はあなたを理解していることを願っています...あなたのモデルにプロパティを追加し、あなたの必要なDataAnnotationを使用してください:

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

次に、このプロパティでdisplayforを使用します。

于 2012-09-07T22:56:06.997 に答える
0

jQueryDatatablesプラグインを使用できます。Javasriptでは、テーブル構成プロパティをオン/オフするだけで、これで大量の「景品」を入手できます。したがって、テーブルの上部に検索ボックスを表示できます。たとえば、列をアルファベットで自動並べ替えると、テーブルの下部に情報行が表示されます。たとえば、「8つのエントリのうちの1つを表示」のようになります。

于 2012-09-08T08:36:00.360 に答える