Yes.
When you use the @model type
directive at the top of your view, you are telling the framework it can expect an instance of that type. The HTML helpers (e.g. Html.DisplayFor
, Html.EditorFor
, etc.) are all based on the type of model that you supply. You can see this if you open your view, and hover your mouse cursor over EditorFor
. You'll see something like this:
string IHtmlHelper<OnlineShop.Models.ViewModels.LoginModel>.DisplayNameFor<string>(
System.Linq.Expressions.Expression<Func<OnlineShop.Models.ViewModels.LoginModel, string>> expression)
Notice that the method is generic and is based on OnlineShop.Models.ViewModels.LoginModel
. This is because these methods are expecting you to pass an instance of OnlineShop.Models.ViewModels.LoginModel
to your view, as that's what you stated using the @model
directive at the top of your view.
No because I know what this exception means but I do not know why I get it in this particular situation. For example for Html.LabelFor it works fine.
The reason it works for LabelFor
is because LabelFor
is looking at metadata for your model, rather than needing an instance of it. By default, it simply creates a label with the name of the property you pass it. In your case, if you called @Html.LabelFor(m => m.Username)
it will create a label HTML element whose text is Username
, but it doesn't need an instance of your viewmodel to do that.
EditorFor
, on the other hand, is both looking at metadata for your Username
property, to create an appropriate input HTML element (e.g. a textbox for a string, or a checkbox for a bool), and also using the value of the Username
property in order to populate that editor (e.g. checking the checkbox). That's why you get the exception when calling Html.EditorFor(m => m.Username)
when you're not giving it an instance of your model.