0

Razorには、後でビューで値がわかるように、ページにHTMLを印刷する方法がありますか?

例:高額な計算の合計を出力したいのですが、その合計はHTMLの項目の前にある必要があります。ただし、以下の例では、常に0が出力されます。合計を1回だけ計算したいと思います。

csharpヘルパーやクライアント側(css、javascriptなど)ではなく、ビューでこれを解決したいと思います

@{
  var sum = 0;
}

<table>
@* I would like to print here the sum which is known after the foreach loop*@
 <tr><td>total: @sum</td></tr>

    @foreach (var item in items)
    {
      <tr>
        @{ 
          var x= item.expensiveCalculation(); 
          sum+= x;
        }
        //print item with x
        <td>@x</td>

      </tr>
    }

</table>

編集:高価なCalculation()がアイテムごとに1回だけ計算されることが非常に重要です!

4

1 に答える 1

4

モデルがビューの要件に適合していません。終止符。

したがって、モデルがビューの要件に適合していない場合は、先に進んでビューモデルを定義し、すべての高価な操作がコントローラー内で実行されるようにします。

それで:

public class ItemViewModel
{
    public decimal Price { get; set; }
    public string Name { get; set; }
}

これで、ビューがビューモデルに強く型付けされ、コストのかかる操作がなくなります。

@model IEnumerable<ItemViewModel>
<table>
    <tr>
        <td>
            total: @Model.Sum(item => item.Price)
        </td>
  </tr>
  @foreach (var item in Model)
  {
      <tr>
          <td>@item.Name - @item.Price<td>
      </tr>
  }
</table>

そして、コントローラーアクション内で、このビューモデルを準備し、ビューに渡します。

public class SomeAction()
{
    IEnumerable<Item> items = ... go and fetch your domain models from wherever you are fetching them
    // now let's build the view model
    var model = new MyViewModel
    {
        Items = items.Select(x => new ItemViewModel
        {
            Name = x.Name,
            Price = x.expensiveCalculation()
        })
    };

    // and we are obviously passing the view model to the view, not the domain model
    return View(model);
}

ご覧のとおり、ビューモデル(Price)の対応するプロパティにバインドするために、コントローラー内の各要素に対して高額な操作を行っていますが、単純に合計しているため、ビュー内でこの高額な操作の価格を支払うことはありません。ビューモデルの事前計算されたプロパティ。

また、次回ASP.NET MVCで問題が発生したときは、ビューモデルが問題の解決策であることを忘れないでください。

于 2012-09-20T12:00:29.033 に答える