Binding nested model with MVC3 on HttpPost
I am new to MVC3.
I have a submit button on a form and I want to bind a model which has 2-3 nested object models with many properties inside.
Is there a way to bind these nested objects without using EditorFor; so that when I submit the form I will take on ActionResult(Object model) on model that is bein开发者_StackOverflow中文版g returned, the nested object models with their values without having to implement hidden values or forms behind on html?
The DefaultModelBinder
works by convention, so for it to work, the form fields must adhere to the MVC naming convention.
If you do not want to use EditorForModel
to create your form, then you will have to implement your own naming convention for every field, and set ViewData.TemplateInfo.HtmlFieldPrefix
for each element. Then, you will have to create a custom ModelBinder to take the form returned, and bind to your models based on your naming convention.
Be aware that this creates some other issues in MVC3, most important of which is that the rendering of unobtrusive validation for DropDownLists and some other items may fail.
For the general case, it is best to use EditorForModel in your view, and to work using MVC's existing conventions. You can create a view which is specific for each nested model. Brad Wilson gives a good overview of the process in this article.
basically you need enough values to identify your model again. So you can go with a Id in a hidden field and all the properties you want to change. To recreate your model either just pass the Id and changed values via basic parameters to your controller-action or write a model-binder - IMHO thats the best way to deal with those situations.
精彩评论