Binding nested model with MVC3 on HttpPost

孤者浪人 提交于 2019-12-07 09:28:30

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/7545515/binding-nested-model-with-mvc3-on-httppost

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