绑定到强类型对象的ASP.NET MVC集合 [英] Binding to a Collection of Strongly-Typed Objects in ASP.NET MVC
问题描述
我有一个包含多个字段的数据类:
I have a data class that contains a number of fields:
public class Person
{
public int id { get; set }
public string Name { get; set; }
public double Rate { get; set; }
public int Type { get; set; }
}
如果我理解<一个href=\"http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx\">Scott Hanselman的接受约束性减排对象数组的,我应该能够创建HTML渲染,看起来像这样的表单视图:
If I understand Scott Hanselman's take on binding arrays of objects, I should be able to create a form view that renders HTML that looks like this:
<input name="Person[0].id" value="26" type="hidden" />
<input name="Person[0].Name" value="Tom Smith" type="text" />
<input name="Person[0].Rate" value="40.0" type="text" />
<select name="Person[0].Type">
<option selected="selected" value="1">Full Time</option>
<option value="2">Part Time</option>
</select>
<input name="Person[1].id" value="33" type="hidden" />
<input name="Person[1].Name" value="Fred Jones" type="text" />
<input name="Person[1].Rate" value="45.0" type="text" />
<select name="Person[1].Type">
<option value="1">Full Time</option>
<option selected="selected" value="2">Part Time</option>
</select>
我应该再能够捕捉到这个数据在我的控制器,看起来像这样的操作方法:
I should then be able to capture this data in my controller with an action method that looks like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult People(Person[] array)
{
// Do stuff with array
}
但它不工作。数组变量总是空。我间preT这为数据绑定不工作。但是,为什么?
But it doesn't work. The array variable is always null. I interpret this as the data binding is not working. But why?
推荐答案
您字段应该指定数组[0] .ID,数组[0]型号及...
Your fields should be named array[0].id, array[0].Type, ...
它们应具有阵列实例的名称,该阵列内的类型的不名称
They should have the name of the array instance, not the name of the Type inside the array.
另外,你可以改变的ActionController到的签名:
人[]人
Alternatively you could change the signature of the actioncontroller to: Person[] Person
您明白了吧: - )
这篇关于绑定到强类型对象的ASP.NET MVC集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!