tidjok tidjok - 2 months ago 9x
ASP.NET (C#) Question

MVC Linq vs Model Dot Notation

I just simply am not understanding the a couple of concepts of this simple MVC View:

@model Models.Company


@Html.TextBoxFor(m => m.CompanyName)
<br />

@Html.DropDownListFor(m => m.Departments, new SelectList(Model.Departments, "Id", "Name"), "Select Department")

Note that
is a property of the Company object that returns a List object.

I understand that the Model of the View is the Company object. What I'm not understanding in the least bit is why LINQ is used to populate the name of the TextBox, why it is used as the name of the DropDownList and why Model Dot Departments is used for the SelectList.

Why not just use Model.CompanyName and Model.Departments? Why bring in LINQ at all?


Do you mean this?:


instead of this?:

@Html.TextBoxFor(m => m.CompanyName)

Because those mean two very different things. The first one (the one you would like to use) doesn't tell TextBoxFor() anything about the model. It just passes a string value. So the resulting text box would have only that string value to use, and nothing about the property or the model which held that property. No model annotations, no validation, nothing. It would be exactly the same as this:

@Html.TextBoxFor("My Company Name")

Heck, it wouldn't even be able to tell the input what to use for the name attribute, which means there'd be no way to bind the model when posting the form back to a server action.

The actual version being used in the code doesn't pass the value of the property, it passes an expression which references the property itself:

m => m.CompanyName

So TextBoxFor() knows the model type, property type, annotations therein, etc. That way it can use any additional information useful to the framework such as validation, helpful messages, type checking, etc.