2017-03-17 76 views
0

我必须将复选框值和文本框值绑定到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> 

我要送的复选框,文本框的值到控制器。 请帮忙。

回答

2

使用MVC提供的HtmlHelpers呈现输入。他们将确保生成的<input/>idname属性的格式可以由MVC ModelBinder处理。

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

将输入包装在<form>中以发布到控制器。通过以下示例,当用户单击“提交”按钮时,模型将发布到“ErrorController”中的“更新”操作。 myFormClass和​​不是必需的,我只是想展示如何在需要时添加它们。

@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> 
} 

LabelFor将试图找到在视图模型的财产[Display(Name="some_resource_key", ResourceType = typeof(Resources))]属性查找翻译后的文本被用作Resources.resx标签。

编辑正如Antoine提到的,您必须为所有ViewModel属性提供输入信息,这些属性将被回传。您可以使用@Html.HiddenFor(m => m[i].Id)呈现<input type="hidden"/>

+3

不要忘记告诉OP把他的模型ID放在'.hidden()' –

+0

它没有用。 :| – user3206357

+1

你没有把表格标签“使用表格...”? – TTCG