MVC model properties and multiple forms on one view

烈酒焚心 提交于 2019-12-12 03:36:28

问题


I have a general question, but something that is killing me, and once explained, will help a lot. I am wondering how the models are preserved in a view. Basically, if I have three different forms on one view, and they all use the same model, but are updating different properties, do they all have the same model state when each form is submitted to its own controller action? Or, if a property of a model is not stored somewhere on page after rendering, does it get lost and not preserved?


回答1:


You can create separate post actions for each form i.e change the forms action so that the state for the model is different. When you post a form and capture the model in controller the state for each will be different .

So steps are:

  • Create separate post actions for each form in the controller.
  • Change the form's action parameter to the one you created in the controller.
  • You can use the common model now.



回答2:


Yes, if there are not enough properties stored on the page itself for ASP.NET MVC to be able to determine which model class to use and reconstruct it, it will be "lost" (lost in the sense that it will not re-build your model object on postback; but you can still rebuild it manually using the FormCollection).

Default model binding works by simply assigning HTML form values to the corresponding properties of the model object. (This isn't absolutely true; for example, you can write a custom model binder, or take other approaches, but for the purpose of what you're asking (default MVC model binding) - it is a HTML form field <-> model property relationship.)

This is the reason why hidden HTML input fields are often used to preserve model properties which are not user-editable.



来源:https://stackoverflow.com/questions/30196865/mvc-model-properties-and-multiple-forms-on-one-view

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