More complex(real-life) modelbinding?

感情迁移 提交于 2020-02-03 10:43:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!