3

Roll with me and imagine the following example:

Public ViewResult GiveMeFruit(int personId, string personName, int personAge, int fruitId){
    Person person = PersonService.GetPerson(personId);
    person.Name = personName;
    person.Age = age;
    person.Fruits.Add(FruitService.GetFruit(fruitId));
    ViewData.Person = person;
    View(ViewData);
}

This should be done better like so

Public ViewResult GiveMeFruit(Person person, IFruit fruit){
    person.Fruits.Add(fruit);
    ViewData.Person = person;
    View(ViewData);
}

I tried proper modelbinding earlier but I couldn't get it to work properly. All the examples show you how it works with one extremely simple type, never with multiple, complex types. How would the modelbinder know what field is for what type? What if there is a fruit1 and a fruit2? How would the binder know what concrete type to use for my IFruit interface? Furthermore I wonder how it would work if I want to give an IEnumerable fruits to my Person.

Boris Callens
  • 90,659
  • 85
  • 207
  • 305

1 Answers1

3

I believe it should go like this :

<input type="text" name="person.Name" value="" />
<input type="text" name="person.Age" value="" />
<input type="text" name="fruit.Property1" value="" />
<input type="text" name="fruit.Property2" value="" />

For collections :

<input type="text" name="fruit[0].Property1" value="" />
<input type="text" name="fruit[0].Property2" value="" />
<input type="text" name="fruit[1].Property1" value="" />
<input type="text" name="fruit[1].Property2" value="" />

Like in this question.

Community
  • 1
  • 1
Çağdaş Tekin
  • 16,592
  • 4
  • 49
  • 58
  • Shouldn`t parameters have Bind prefix in this case? Or it`s just another convention i`ve missed? – Arnis Lapsa Apr 29 '09 at 08:23
  • @Arnis L. No, the parameters don't have to have the Bind prefix for that to work. Check this post out : http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx – Çağdaş Tekin Apr 29 '09 at 13:17