添加另一个"宠物及QUOT;以模型形式 [英] Adding another "Pet" to a Model Form
问题描述
简化的例子。
我有有几个领域模型:
OwnerFirstName
OwnerLastName
List<Pet> Pets (Pet is a few string fields)
用户界面需要允许用户添加任意数量的新宠物。对于宠物入境的用户界面是一个MVC模板的 _petEditor.cshtml
客户端,如何添加一个新的宠物示范的宠物收集,然后从_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 ?
当用户提交表单,MVC将获得与添加的所有宠物的典范。
When the user submits the form, MVC will get a model with all the Pets added.
推荐答案
您可以使用JavaScript来进行后动态创建索引的投入了。作为一个例子创建一个虚拟的一套克隆,当你点击一个添加宠物按钮,显示输入(假定宠物属性显示在表中使用id ='宠物')
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>
请注意使用虚拟索引以prevent这一个被调回
Note the use of a dummy indexer to prevent this one being posted back
和脚本
$('#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());
}
这篇关于添加另一个&QUOT;宠物及QUOT;以模型形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!