将复选框和文本框绑定到viewmodel

时间:2017-03-17 14:29:25

标签: c# asp.net-mvc

我必须将复选框值和文本框值绑定到model.Here我正在使用模型来检索和发布数据。 我尝试了一些选项,但它没有用。

以下是我的代码:

@model IEnumerable<ALDS.Web.Areas.AR.Models.ReportViewModel>

@{
    ViewBag.Title = "Standings";
}


    <table class="table table-bordered">
        <thead>
            <tr>
                <th>LR Date</th>
                <th>LR Line No</th>
                <th>Issue</th>
                <th>Correction Response</th>
                <th>Remarks</th>
                <th>Submission</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @item.InsertDate
                    </td>
                    <td>
                        @item.LRLineID <a href="">View</a>
                    </td>
                    <td>Margin % incorrect</td>
                    <td><label for="cbox1">Corrected</label>  <input type="checkbox" name="Corrected" value="@item.Status"  />     <label for="cbox1">Neglected</label>  <input type="checkbox" name="Neglected" value="@item.Status"/></td>
                    <td><input type="text" value="@item.Comments"/></td>
                    <td><a href="@Url.Action("Update","Error",Model)">Submit</a></td>

                    </tr>
            }
        </tbody>
    </table>

我必须将复选框和文本框值发送到控制器。 请帮忙。

1 个答案:

答案 0 :(得分:2)

使用MVC提供的HtmlHelpers渲染输入。他们将确保生成的id的{​​{1}}和name属性采用可由MVC ModelBinder处理的格式。

此外,要回发对象列表,请使用<input/>循环,以便项目获得ModelBinder理解的索引。

将输入包裹在for中以发布到Controller。通过以下示例,模型将发布到&#34;更新&#34;动作&#34; ErrorController&#34;当用户点击&#34;提交&#34;按钮。 <form>myFormClass不是必需的,我只想展示如何在需要时添加它们。

myFormId

@using(Html.BeginForm("Update", "Error", FormMethod.Post, new { @class = "myFormClass", id = myFormId })) { for (var i = 0; i < Model.Length; i++) { @Html.LabelFor(m => m[i].Status) @Html.CheckBoxFor(m => m[i].Status) @Html.LabelFor(m => m[i].Comments) @Html.TextAreaFor(m => m[i].Comments) // multi line @Html.TextBoxFor(m => m[i].Comments) // single line } <button type="submit">Submit</button> } 将尝试在ViewModel中的属性上查找LabelFor属性,以查找要在Resources.resx中用作标签的已翻译文本。

编辑正如Antoine所提到的,您必须为将要回发的所有ViewModel属性提供输入。您可以使用[Display(Name="some_resource_key", ResourceType = typeof(Resources))]呈现<input type="hidden"/>