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
439 views
in Technique[技术] by (71.8m points)

c# - ASP.Net MVC - model with collection not populating on postback

I have an ASP.Net MVC application with a model which is several layers deep containing a collection.

I believe that the view to create the objects is all set up correctly, but it just does not populate the collection within the model when I post the form to the server.

I have a piece of data which is found in the class hierarchy thus:

person.PersonDetails.ContactInformation[0].Data;

This class structure is created by LinqToSQL, and ContactInformation is of type EntitySet<ContactData>. To create the view I pass the following:

return View(person);

and within the view I have a form which contains a single text box with a name associated to the above mentioned field:

<%= Html.TextBox("person.PersonDetails.ContactInformation[0].Data")%>

The post method within my controller is then as follows:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create (Person person)
{
  //Do stuff to validate and add to the database 
}

It is at this point where I get lost as person.PersonDetails.ContactInformation.Count() ==0. So the ModelBinder has created a ContactInformation object but not populated it with the object which it should hold (i.e ContactData) at index 0.

My question is two fold: 1. Have I taken the correct approach.. i.e. should this work? 2. Any ideas as to why it might be failing to populate the ContactInformation object?

Many thanks, Richard

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think that your model is too complex for the default model binder to work with. You could try using multiple parameters and binding them with prefixes:

public ActionResult Create( 
    Person person,
    [Bind(Prefix="Person.PersonDetails")]
    PersonDetails details,
    [Bind(Prefix="Person.PersonDetails.ContactInformation")] 
    ContactInformation[] info )
{
      person.PersonDetails = details;
      person.PersonDetails.ContactInformation = info;

      ...
}

Or you could develop your own custom model binder that would understand how to derive your complex model from the form inputs.


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

...