Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc uppercase Model vs lowercase model

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?

like image 587
Paritosh Avatar asked Apr 25 '14 12:04

Paritosh


1 Answers

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.

like image 87
Ehsan Sajjad Avatar answered Oct 20 '22 09:10

Ehsan Sajjad