ASP.NET MVC razor view, post to a different model from the original model binding?

一曲冷凌霜 提交于 2019-12-08 07:26:55

问题


Well I have a group controller and view in the project, in which the model binding is GroupViewModel. But the group page is complex, and users will be able to make discussion topics. On this group view page, I have forms that allow users to post topics/replies. The model used for these forms can be TopicViewModel or ReplyViewModel, but the original model binding is only for GroupViewModel. It is declared at the beginning of the cshtml page:

@model MyProject.ViewModels.GroupBrowseViewModel

So I wonder, is it possible to have forms bind to different view model from the one declared at the top? If so, how to achieve this?


回答1:


Model binding really has nothing to do with the model used in your razor view. At least not technically.

The first thing you have to understand is that there is no magic here. This is straight HTTP posted values, and if you don't understand how HTTP posting works, I suggest you read up on it. It's just a series of name/value pairs.

When you post, the routing framework looks at the selected action method, and the parameters that method takes, then it creates new instances of those parameters, and tries to match them up with similarly named values from the posted values.

So, in other words, there is no direct connection here between the model you use on the page, and the model used in the posted controller action. It's all based on naming convention. This naming convention is "helped" by the model you declare on the page, and the Html helpers create form fields with names that match up to model entries so that the model binder can figure these out more easily.

So, what this means is that in order to post to a different action, with a different model, all you need are fields in your form that have the names that the new model expects.

This can be done in a number of ways, from defining those fields manually, to using Partial view in which you pass an instance of the model you intend to post to as the model parameter.




回答2:


You can use 2 partial views in the same view, and switch from the controller which one to show.

Or you can make a new ViewModel and this view model will contain references to both of your views, and in the view html based on your logic your can switch reading from any child ViewModel.



来源:https://stackoverflow.com/questions/30416615/asp-net-mvc-razor-view-post-to-a-different-model-from-the-original-model-bindin

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