Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - 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:

<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. I interpret this as the data binding is not working. But why?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Alternatively you could change the signature of the actioncontroller to: Person[] Person

You get the point :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...