在购物车索引视图(Razor视图引擎)中需要帮助Razor语法

时间:2011-07-12 00:23:13

标签: asp.net asp.net-mvc asp.net-mvc-3 razor

在第一次使用时,我喜欢它,它感觉不那么杂乱,然后webforms<%:%>查看引擎, 但在进一步使用它时,我不禁注意到它对其“{”括号放置位置和其他情况过于敏感。它在较旧的视图引擎不那么挑剔的点上给出了错误。

例如下面的代码会产生错误,因为表单助手关闭括号} 在</table>标记下。如果我将它放在</tbody>之上,它就可以了!但我不需要 因为提交按钮输入必须嵌套在其中,我不想将按钮输入放入表中。

@model CartTest.Models.Cart

@{
    ViewBag.Title = "Index";
}

<h2>Cart Index</h2>

<table width="80%" align="center">
  <thead>
    <tr>
      <th align="center">Quantity</th>
      <th align="left">Item</th>
      <th align="right">Price</th>
      <th align="right">Subtotal</th>
    </tr>
  </thead>
  <tbody>
  @{int index = 0;}
  @using (Html.BeginForm("UpdateCart","Cart"))
  {
    foreach (var line in Model.Lines)
    {
      <tr>
        @Html.Hidden("Lines.Index", index)
        <td align="center">@Html.TextBox("Lines[" + index + "].Quantity", line.Quantity)</td>
        <td align="left">@line.Product.Name</td>
        <td align="right">@line.Product.Price</td>
        <td align="right">@(line.Quantity * line.Product.Price)</td>
        <td align="right">@Html.ActionLink("Remove", "RemoveItem", new { productId = line.Product.ProductID }, null)</td>
      </tr>
      index++;
    }
  </tbody>
  <tfoot></tfoot>
</table>

<input type="submit" value="Update Cart" />
}

2 个答案:

答案 0 :(得分:3)

它在</tbody>之上工作的原因是因为你在开头<tbody>内声明了BeginForm。它们必须正确嵌套才能工作。如果您不想将输入按钮放在表格内,则将BeginForm移动到表格元素之外,以使开始和结束括号处于同一级别。

    @using (Html.BeginForm("UpdateCart","Cart"))
    {

    <table width="80%" align="center">

    <thead><tr>
    <th align="center">Quantity</th>
    <th align="left">Item</th>
    <th align="right">Price</th>
    <th align="right">Subtotal</th>
    </tr></thead>

    <tbody>

    @{int index = 0;}

    foreach (var line in Model.Lines)
    {
    <tr>
    @Html.Hidden("Lines.Index", index)
    <td align="center">@Html.TextBox("Lines[" + index + "].Quantity", line.Quantity)</td>
    <td align="left">@line.Product.Name</td>
    <td align="right">@line.Product.Price</td>
    <td align="right">@(line.Quantity * line.Product.Price)</td>
    <td align="right">@Html.ActionLink("Remove", "RemoveItem", new { productId = line.Product.ProductID }, null)</td>

    </tr>
        index++;

} 
    </tbody>
    <tfoot>
    </tfoot>
    </table>

    <input type="submit" value="Update Cart" />
    }

答案 1 :(得分:0)

移动

@{int index = 0;}
@using (Html.BeginForm("UpdateCart","Cart"))
{

在你的桌子上方,所以整个表格都在表格标签内。