问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/798127/more-complexreal-life-modelbinding