views:

188

answers:

1

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.

+4  A: 

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.

çağdaş
How about an IList<IFruit>?
borisCallens
Please see my edit.
çağdaş
Shouldn`t parameters have Bind prefix in this case? Or it`s just another convention i`ve missed?
Arnis L.
@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ş