ASP.NET MVC post 模型的示例?
我正在观看 关于 MIX 的 ASP.NET MVC 的 HaHaa 演示,他们提到使用帖子模型,我猜他们是说您可以使用仅用于发布的模型。我曾尝试寻找这方面的例子。我不明白他们在说什么吗?有谁有一个例子说明这如何在强类型视图中工作,其中视图模型和帖子模型不是同一类型?
I was watching the HaHaa presentation on ASP.NET MVC from MIX and they mentioned using a Post Model where I guess they were saying you could use a model that was ONLY for posting. I have tried looking for examples for this. Am I not understanding what they are saying? Does anyone have an example of how this might work in a strongly typed view where the view model and post model are not of the same type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
下面是 ScottGu 的示例,稍作扩展。正如 @SLaks 所解释的,当收到 POST 时,MVC 将尝试创建一个新的 MyPostName 对象并将其属性与 from 字段相匹配。它还将使用匹配和验证的结果更新 ModelState 属性。
当操作返回视图时,它也必须为其提供模型。但是,视图不必使用相同的模型。事实上,视图可以使用包含扩展数据的不同模型进行强类型化,例如,它可以将导航属性绑定到数据库表中的外部键;如果是这种情况,从 POST 模型映射到视图模型的逻辑将包含在 POST 操作中。
Below is ScottGu's example expanded a bit. As @SLaks explained, when the POST is received, MVC will try to create a new MyPostName object and match its properties with the from fields. It will also update the ModelState property with the results of the matching and validation.
When the action returns the view, it has to provide a model for it as well. However, the view doesn't have to use that same model. In fact, the view can be strongly typed with a different model, that contains the expanded data, for example it can have navigation properties bound to external keys in the DB table; and if that's the case, the logic to map from the POST model to the view model will be contained in the POST action.
POST 模型仅用于将数据传递到您的操作方法中。
POST 操作发送到其视图的模型不需要与其接收的模型相关(通常不会)。
同样,初始 GET 操作(首先显示表单)传递到其视图(提交到 POST 操作)的模型不需要与 POST 操作采用的模型相关(尽管通常将是相同的模型)
只要它具有与您的输入参数匹配的属性,您就可以使用您想要的任何模型作为 POST 操作的参数。
The POST model would only be used to pass the data into your action method.
The model that the POST action sends to its view doesn't need to be related to the model that it received (and usually will not be).
Similarly, the model that the initial GET action (that shows the form in the first place) passes to its view (which submits to the POST action) doesn't need to be related to the model that the POST action takes (although it usually will be the same model)
As long as it has properties that match your input parameters, you can use any model you want for the parameter to the POST action.