ASP.NET MVC 3-发布前从集合中添加/删除 [英] ASP.NET MVC 3 - Add/Remove from Collection Before Posting
问题描述
我有一个包含集合的模型,例如:
I have a model that contains a collection, such as this:
class MyModel
{
public List<MySubModel> SubModels { get; set; }
}
在视图中,我想在提交之前使用Javascript从此列表中动态添加/删除.现在我有这个:
In the view, I want to dynamically add/remove from this list using Javascript before submitting. Right now I have this:
$("#new-submodel").click(function () {
var i = $("#submodels").children().size();
var html = '<div>\
<label for="SubModels[' + i + '].SomeProperty">SomeProperty</label>\
<input name="SubModels[' + i + '].SomeProperty" type="textbox" />\
</div>'
$("#submodels").append(html);
});
这有效,但是很丑.而且,如果我想显示现有项目的标签/文本框,也没有一种干净的方法(无需重复).
This works, but it's ugly. And, if I want to show those labels/textboxes for the existing items, there's no clean way to do that either (without duplicating).
我觉得我应该能够使用Razor助手或类似的工具.有任何想法吗?帮我保持干燥.
I feel like I should be able to use Razor helpers or something to do this. Any ideas? Help me stay DRY.
推荐答案
如果您要删除或添加div,则可能会导致意外错误.例如,您有4个项目,则删除第一个项目,然后 $('#submodels').children().size()
将返回3,但最后插入的div具有名称属性值设置 SubModels [3] .SomeProperty
会导致冲突.并且,如果您发布的值包含 SubModels [1]
但不包含 SubModels [0]
,则默认模型绑定程序将无法绑定列表(它将绑定为null).我必须努力学习这一点...
You approach may lead to unexpected errors if you when you are removing or adding the divs. For example you have 4 items, you remove the first item, then $('#submodels').children().size()
will return 3, but your last inserted div has the name attribute value set SubModels[3].SomeProperty
which results in a conflict. And if your posted values contain SubModels[1]
but not SubModels[0]
the default model binder will fail to bind the list (it will bind it as null). I had to learn this the hard way...
为消除上述问题(和您的问题),我建议您执行以下操作:
To eliminate the aforementioned problem (and your's) I suggest you do something like this:
$("#addBtn").click(function() {
var html = '<div class="submodel">\
<label>SomeProperty</label>\
<input type="textbox" />\
</div>'; // you can convert this to a html helper!
$("#submodels").append(html);
refreshNames(); // trigger after html is inserted
});
$(refreshNames); // trigger on document ready, so the submodels generated by the server get inserted!
function refreshNames() {
$("#submodels").find(".submodel").each(function(i) {
$(this).find("label").attr('for', 'SubModels[' + i + '].SomeProperty');
$(this).find("label").attr('input', 'SubModels[' + i + '].SomeProperty');
});
}
Then your view (or even better an EditorTemplate for the SubModel type) can also generate code like:
<div class="submodel">
@Html.LabelFor(x => x.SomeProperty);
@Html.EditorFor(x => x.SomeProperty);
</div>
还可以将代码生成转换为html helper类,并在EditorTemplate和JavaScript代码中使用
It would also be possible to convert the code generation to a html helper class, and use it in the EditorTemplate and in the JavaScript code
这篇关于ASP.NET MVC 3-发布前从集合中添加/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!