Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 938
bytedev Avatar asked Dec 09 '22 22:12

bytedev


1 Answers

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.

like image 141
VJAI Avatar answered Feb 23 '23 04:02

VJAI