asp.net-mvc ASP.NET MVC 在模型中绑定数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2080355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC bind array in model
提问by cmv
This is somewhat a two-part question (please let me know if they should be split up).
这是一个由两部分组成的问题(如果它们应该分开,请告诉我)。
1) I have a model class with an array of objects contained inside it. I would like to be able to bind this automatically so I can accept a single pollModelargument in my controllers.
1)我有一个模型类,其中包含一组对象。我希望能够自动绑定它,这样我就可以pollModel在我的控制器中接受一个参数。
public class pollResponseModel
{
public long id { get; set; }
public long pollID { get; set; }
public string text { get; set; }
public long count { get; set; }
}
public class pollModel
{
public long id;
public long entID { get; set; }
public string question { get; set; }
public DateTime posted { get; set; }
public DateTime expiration { get; set; }
public pollResponseModel[] responses { get; set; }
}
The problem is that I'm not sure how to bind the responsesfield, seeing as it can be any arbitrary size. Well, I can bind it properly when displaying the edit view, but that's about it. That leads me to the second part of my question:
问题是我不确定如何绑定该responses字段,因为它可以是任意大小。好吧,我可以在显示编辑视图时正确绑定它,但仅此而已。这导致我进入我问题的第二部分:
2) What's an acceptable way of dynamically creating and removing data in a list on the client, so that it can be bound to a model and accessed in its modified form on the server? I envision the creation/removal process working like the iPhone list GUI: a single +button will add a new element, and a -button on each row of data will remove it from the list. I would imagine jQuery is an appropriate starting point but my JS skills are very limited.
2)在客户端的列表中动态创建和删除数据的可接受方式是什么,以便它可以绑定到模型并在服务器上以其修改的形式访问?我设想创建/删除过程像 iPhone 列表 GUI 一样工作:单个+按钮将添加一个新元素,-每行数据上的一个按钮将其从列表中删除。我想 jQuery 是一个合适的起点,但我的 JS 技能非常有限。
回答by womp
Check out this article by Phil Haack : Model Binding To a List. It explains exactly what you need to do to bind to list properties, or properties that are complex objects.
查看 Phil Haack 的这篇文章:模型绑定到列表。它准确地解释了绑定到列表属性或复杂对象属性所需的操作。
Essentially you just have to construct your POST data in the correct way for the model binder to parse it. The article explains how to add hidden index fields and represent your complex properties in your form.
本质上,您只需要以正确的方式构建 POST 数据,模型绑定器就可以解析它。本文解释了如何添加隐藏的索引字段并在表单中表示复杂的属性。

