添加另一个“宠物"到模型表单 [英] Adding another "Pet" to a Model Form

查看:39
本文介绍了添加另一个“宠物"到模型表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简化示例.

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

所有者名字所有者姓氏列表<宠物>Pets(宠物是几个字符串字段)

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

客户端,我如何向模型的宠物集合中添加一个新的宠物,然后从 _petEditor.cshtml 为宠物添加一组新的字段?

当用户提交表单时,MVC 会得到一个添加了所有宠物的模型.

解决方案

您可以使用 javascript 为回发动态创建索引输入.例如,创建一组虚拟输入,当您单击添加宠物"按钮时,这些输入将被克隆和显示(假设宠物属性显示在带有 id='Pets' 的表中)

注意使用虚拟索引器来防止这个被回发

还有剧本

$('#AddButton').click(function() {var index = (new Date()).getTime();var clone = $('#NewPet').clone();//更新克隆的索引clone.html($(clone).html().replace(/[#]/g, '[' + index + ']'));clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));$('#Pets tbody').append(clone.html());}

Simplified example.

I have a Model which has a few fields:

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

The UI needs to allow the user to add any number of new Pets. The UI for the Pet entry is an MVC template _petEditor.cshtml

Client side, how do I add a new Pet to the Model's Pet collection, then add a new set of fields for the Pet from _petEditor.cshtml ?

When the user submits the form, MVC will get a model with all the Pets added.

解决方案

You could use javascript to dynamically create indexed inputs for post back. As an example create a dummy set of inputs that are cloned and displayed when you click an 'add pet' button (assumes Pet properties are displayed in a table with id='Pets')

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

Note the use of a dummy indexer to prevent this one being posted back

And the script

$('#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());
}

这篇关于添加另一个“宠物"到模型表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆