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?
}
I never noticed this behaviour in ASP.NET MVC before but the ViewModel (if its not being supplied) seems to be be getting instantiated.
Could someone clarify this behaviour.
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,
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With