Will ViewModel param never be null in ASP.NET MVC 3 action?

后端 未结 3 1437
死守一世寂寞
死守一世寂寞 2021-01-13 16:47

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\".



        
3条回答
  •  情歌与酒
    2021-01-13 17:30

    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.

    Why this happens?

    This is how the DefaultModelBinder works,

    1. Create an instance of the view model.

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

    3. Return the created instance.

    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.

    That makes little sense right?

    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.

提交回复
热议问题