试图为ViewBag设置值

时间:2011-12-15 13:08:10

标签: viewbag

有人可以告诉我为什么这不起作用吗?

我收到错误No overload for method 'Write' takes 0 arguments。这发生在foreach的第一行,我设置了ViewBag.InvoiceTotal。

@foreach (var invoice in Model.Invoices)
{
    @{ ViewBag.InvoiceTotal = (invoice.Product.Price * invoice.Quantity).ToString("c"); }

    <tr>
        <td>
            @Html.DisplayFor(modelItem => invoice.InvoiceDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => invoice.Company.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => invoice.Product.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => invoice.Quantity)
        </td>
        <td>
            @Html.DisplayFor(modelItem => invoice.Product.Price)
        </td>
        <td>
            @ViewBag.InvoiceTotal
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id = invoice.InvoiceId }) |
            @Html.ActionLink("Details", "Details", new { id = invoice.InvoiceId }) |
            @Html.ActionLink("Delete", "Delete", new { id = invoice.InvoiceId })
        </td>
    </tr>
}

2 个答案:

答案 0 :(得分:1)

你有一个额外的@

@foreach (var invoice in Model.Invoices)
 { 
  { 
  ViewBag.InvoiceTotal = (invoice.Product.Price * invoice.Quantity).ToString("c"); 
  } 
}

这很有效。

答案 1 :(得分:0)

       @foreach (var invoice in Model.Invoices)
            {
                 ViewBag.InvoiceTotal = (invoice.Product.Price * invoice.Quantity).ToString("c"); 

                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => invoice.InvoiceDate)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => invoice.Company.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => invoice.Product.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => invoice.Quantity)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => invoice.Product.Price)
                    </td>
                    <td>
                        @ViewBag.InvoiceTotal
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id = invoice.InvoiceId }) |
                        @Html.ActionLink("Details", "Details", new { id = invoice.InvoiceId }) |
                        @Html.ActionLink("Delete", "Delete", new { id = invoice.InvoiceId })
                    </td>
                </tr>
            }