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\".
When the action method parameter is a complex type, then the DefaultModelBinder class uses reflection to obtain the set of public properties and then binds to each of them. For complex types it uses Activator.CreateInstance(typeToCreate);
Then ValueProviders will be used to obtain the values of these properties. Remember that model binders aren't locked to specific sources, but they can build object from an aggregate of sources.
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.
MVC will try to take the values that were sent via a POST/GET and "automagically" bind them to the properties of the model. This is done by the default model binder. In most cases, the default model binder will do everything you need it to.
You can look deeper into custom model binding (and might get a deeper understanding of it), but looking into the IModelBinder interface -- it contains a single method called BindModel. In this method, you would pretty much take whatever is in the ControllerContext.HttpContext.Request and fill in your class properties (basically the same thing the default model binder does). Using a custom model binder has a few more hoops you need to jump through, but will give you the idea of the binding lifecycle.
The short answer: With the default model binder, it won't be null.
HTH