简体   繁体   English

绑定到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; }
}

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: 如果我理解Scott Hanselman对绑定对象数组的看法,我应该能够创建一个表单视图,呈现如下所示的HTML:

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

But it doesn't work. 但它不起作用。 The array variable is always null. 数组变量始终为null。 I interpret this as the data binding is not working. 我解释这一点,因为数据绑定不起作用。 But why? 但为什么?

Your fields should be named array[0].id, array[0].Type, ... 您的字段应命名为array [0] .id,array [0] .Type,...

They should have the name of the array instance, not the name of the Type inside the array. 它们应该具有数组实例的名称,而不是数组中Type的名称。

Alternatively you could change the signature of the actioncontroller to: Person[] Person 或者,您可以将actioncontroller的签名更改为:Person [] Person

You get the point :-) 你明白了这一点:-)

<input name="Person[0].Rate" value="40.0" type="text" />

应该:

<input name="array[0].Rate" value="40.0" type="text" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM