ASP.NET MVC剃刀视图,发布到与原始模型绑定不同的模型? [英] ASP.NET MVC razor view, post to a different model from the original model binding?

查看:91
本文介绍了ASP.NET MVC剃刀视图,发布到与原始模型绑定不同的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中有一个组控制器和视图,其中模型绑定为GroupViewModel.但是小组页面很复杂,用户可以进行讨论.在此组视图页面上,我具有允许用户发布主题/回复的表单.用于这些表单的模型可以是TopicViewModel或ReplyViewModel,但是原始模型绑定仅用于GroupViewModel.它是在cshtml页的开头声明的:

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?

推荐答案

模型绑定确实与剃刀视图中使用的模型无关.至少从技术上来说不是.

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

您首先要了解的是这里没有魔术.这是直接的HTTP发布值,如果您不了解HTTP发布的工作原理,建议您继续阅读.这只是一系列名称/值对.

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.

因此,换句话说,您在页面上使用的模型与发布的控制器操作中使用的模型之间没有直接联系.全部基于命名约定.您在页面上声明的模型将帮助"此命名约定,HTML助手将创建具有与模型条目匹配的名称的表单字段,以便模型绑定程序可以更轻松地找出它们.

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.

这篇关于ASP.NET MVC剃刀视图,发布到与原始模型绑定不同的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆