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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0