Binding nested model with MVC3 on HttpPost
Asked Answered
T

2

4

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 being returned, the nested object models with their values without having to implement hidden values or forms behind on html?

Trover answered 25/9, 2011 at 12:36 Comment(1)
Try my solution #47645199Furthermore
M
0

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.

Machicolate answered 25/9, 2011 at 12:41 Comment(0)
P
2

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.

Panelist answered 25/9, 2011 at 14:36 Comment(0)
M
0

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.

Machicolate answered 25/9, 2011 at 12:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.