将视图模型参数永远不会在ASP.NET MVC 3行动空? [英] Will ViewModel param never be null in ASP.NET MVC 3 action?

查看:106
本文介绍了将视图模型参数永远不会在ASP.NET MVC 3行动空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就当该方法是通过ASP.NET MVC打电话给我的视图模型参数永远不会在下列情况下空?例如使用URL... /首页/索引。

Will my viewModel param never be null in the following situation when the method is called through ASP.NET MVC? For example using the URL ".../Home/Index".

public ViewResult Index(HomeViewModel viewModel)
{
  // .. do stuff...viewModel is never null here when called within ASP.NET?
}

我从来没有看到在ASP.NET MVC这一行为之前,但视图模型(如果它不被提供)似乎有越来越实例化。

I never noticed this behaviour in ASP.NET MVC before but the ViewModel (if its not being supplied) seems to be be getting instantiated.

有人能澄清这个问题。

推荐答案

是的,你总是会得到一个视图模型的实例,偶虽然没有任何参数存在可分配给视图模型的请求。

Yes you will always get an instance of a view model even-though there is no any parameter in exists in the requests that can be assigned to the view model.

为什么出现这种情况?

这是怎么了 DefaultModelBinder


  1. 创建视图模型的实例。

  1. Create an instance of the view model.

迭代模型中的属性,并要求该值提供商发现值,并设置找到的值的属性

Iterate the properties in the model and ask the value providers to find values and set the found values to the properties.

返回创建的实例。

如果您看到的步骤 DefaultModelBinder 它并不关心是否有请求可被设置为模型实例,它只是提前启动,并创造任何价值实例,然后填写属性。

If you see the steps the DefaultModelBinder it doesn't care if there is any value in the request that can be set to the model instance it's just start ahead and create the instance and then fill the properties.

这没有什么意义吧?

这将是更加复杂的模型绑定来检查请求是否含有该模型的属性相匹配的值,然后创建一个实例。

It would be more complex for the model binder to check the request whether it contains any value that matches the property of the model and then create an instance.

这篇关于将视图模型参数永远不会在ASP.NET MVC 3行动空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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