在foreach ASP MVC中使用关键字



在我的视图中,我需要在每次迭代中使用一个表单,但如果我把@using放在foreach中,它就不起作用,

@foreach (var item in list)
{
    <tr>
        <td>@Html.DisplayName(item.name)</td>
        @using(Html.BeginForm("Index", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
        {
        <td>@Html.TextBoxFor(model=> model.quantity, new { @class = "form-control" })</td>
        <td>@Html.DropDownList("idid", (IEnumerable<SelectListItem>)ViewData["list"], "Select ...", new { @class = "form-control" })</td>
        <td>@Html.DisplayFor(model=> model.id, new { Value = item.id })</td>
        <td><input type="submit" class="btn btn-default" value="Send" /></td>

        }
    </tr>
}

您的HTML格式不正确,我怀疑这就是您出现错误的原因。创建表单元素时,它将包含<td>元素,而不是完整的表。当它生成时,它将是这样的。

<table>
    <tr>
        <td></td>
        <form>
            <td></td>
            <td></td>
            <td></td>
        </form>
    </tr>
</table>

必须将表单放在<td>元素内部或<table>元素外部,才能生成有效的HTML。

<form>
    <table>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </table>
</form>

<table>
    <tr>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
        <td><form><!-- input and other html elements here --></form></td>
    </tr>
</table>

最新更新