添加另一个" Pet"到模型表格

时间:2014-06-03 23:00:56

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

简化示例。

我有一个包含几个字段的模型:

OwnerFirstName
OwnerLastName
List<Pet> Pets (Pet is a few string fields)

用户界面需要允许用户添加任意​​数量的新宠物。 Pet条目的UI是MVC模板 _petEditor.cshtml

客户方面,如何将新Pet添加到Model的Pet集合中,然后从_petEditor.cshtml为Pet添加一组新字段?

当用户提交表单时,MVC将获得一个包含所有Pets的模型。

1 个答案:

答案 0 :(得分:5)

您可以使用javascript动态创建回发的索引输入。例如,创建一组虚拟输入,当您单击“添加宠物”时,克隆并显示这些输入。按钮(假设宠物属性显示在id =&#39; Pets&#39;的表格中)

<div id="NewPet" style="display:none">
  <tr>
    <td><input type="text" name="Pets[#].Type value /></td>
    <td><input type="text" name="Pets[#].Breed value /></td>
    <td>.....</td> // more properties of Pet
    <td><input type="hidden" name="Pets[#].Index" value ="%"/></td>
  </tr>
</div>

请注意使用虚拟索引器来防止将其重新发布回来

脚本

$('#AddButton').click(function() {
  var index = (new Date()).getTime(); 
  var clone = $('#NewPet').clone();
  // Update the index of the clone
  clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
  clone.html($(clone).html().replace(/"%"/g, '"' + index  + '"'));
  $('#Pets tbody').append(clone.html());
}