【问题标题】:MVC 4: Create HTML textboxes dynamically with JQUERY and PartialViewResult. How to fill the model if the code is added dynamically?MVC 4:使用 JQUERY 和 PartialViewResult 动态创建 HTML 文本框。如果代码是动态添加的,如何填充模型?
【发布时间】:2015-03-09 15:39:02
【问题描述】:

我正在用 JQUERY 之类的方式创建表单输入字段

$('#students').live('change', function () {
  var value = $(this).val();
  if (value) {
    $.ajax({
      type: "GET",
      timeout: 10000,
       url: "@Url.Action(MVC.Company.ManageWorkReport.GetStudent())",
       data: { studentId: value },
       cache: false,
       success: function (data) {
         if (data) {
           $("#students tbody").html(data);                                
         }
       },
       error: function (xhr, status, error) {
         alert(xhr.responseText);
       }
     });
  }
  return false;
});

插入数据的HTML代码是

@using (Html.BeginDefaultForm(MVC.Company.ManageWorkReport.Create()))
{
  <table class="table table-striped table-bordered bootstrap-datatable datatable" id="students">
    <thead>
      <tr>
        <th>Ime in Priimek</th>
        <th>Vrsta</th>
        <th>Začetek dela</th>
        <th>Konec dela</th>
        <th>Enota</th>
        <th>Cena za enoto</th>
        <th>Količina</th>
        <th>Neto znesek</th>
        <th>Bruto znesek</th>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td colspan="11">Podatek še ne obstaja</td>
      </tr>
    </tbody>
  </table>
  @Html.SimpleSubmitAndCancelButton(Translations.Global.SAVE, Translations.Global.CANCEL)
}

和 C#

[HttpGet]
public virtual PartialViewResult GetStudent(int studentId)
{
  StudentsWorksReportsFormModel studentsWorksReportsFormModel = new StudentsWorksReportsFormModel();
  .....
  var view = PartialView("StudentWorkReportResult", studentsWorksReportsFormModel);        
  return view;

}

问题是当我在表单中输入数据并单击提交按钮时,模型始终为空。如果我用 JQUERY 填充页面然后在文本字段中输入数据,为什么模型是空的?如何填充模型,我可以在数据库中插入数据。

【问题讨论】:

    标签: javascript c# jquery asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    为了让模型绑定器为您选择新值,您需要设置控件的名称属性。

    每个项目都需要索引并设置属性名称。

    因此,例如,如果您的集合是 MyCollection 以在第一项上设置 Name 属性,您将添加以下内容:

    Name="MyCollection[0].Name"
    

    第二个等:

    Name="MyCollection[1].Name"
    

    The Features and Foibles of ASP.NET MVC Model Binding

    如果您要返回部分视图,则需要遍历您的集合,如下所示:

    @for(i = 0; i < Model.StudentWorkReportFormModel.Count; i++)
    {
        @Html.TextBoxFor(modelItem => Model.StudentWorkReportFormModel[i].StartDate})
    }
    

    【讨论】:

    • 感谢您的回答,但我正在像 @Html.TextBoxFor(modelItem => item.StudentWorkReportFormModel.StartDate}) 这样的部分视图中创建文本框,如果自动创建名称参数,我该如何覆盖?跨度>
    • @senzacionale 没问题,您需要将它们编入索引以便循环播放。看我的更新。 :)
    • @senzacionale 没有问题。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多