I'm working on a MVC 5 project, very new to MVC. I noticed this line in the code:
@Html.DropDownListFor(model => model.ContractorId, Model.Contractors)
the directive on the top of the page is:
@model Project.Models.ContractViewModel
The ContractViewModel class does have a Contractors object in it.
public IEnumerable<SelectListItem> Contractors
I'm just a little confused on the capital M (Model.Contractors), does Model always refer to the object passed in the @model? Then what is the difference between using Model.Contractors and model.Contractors?
Model actually represents an instance of the class that is your model and model is an alias for lambda expression.
When you write @Model
in your view you are using the object of ContractViewModel
which is passed from Controller action, if it is not passed from View it can be null and accessing any property of Model can throw Null Reference Exception and writing Model.Contractors
you basically mean ContractViewModel.Contractors
and when you write a html helper you need to write an alias for it, its not mandatory to write model
you can write anything.
for example:
@Html.DropDownListFor(m=> m.ContractorId, Model.Contractors)
It is just an alias to access the model properties inside Html Helper.
When you write @model Project.Models.ContractViewModel
at the top of View that is a different thing, in this case we are defining the model of view that it will take instance of Project.Models.ContractViewModel
, actually our view is now strongly typed to instance of class Project.Models.ContractViewModel
.
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