Ok I just discovered about the EditorForModel
in MVC and I want to know when I should use this instead of an EditorFor
on each of my property? And why does when I add a strongly typed view it does not use this and build an EditorFor
on every property?
I'm late on this... but thanks for the info!
Since the accepted answer is a link-only answer (and was removed), I thought I'd actually answer the question derived from Brad Wilson's Blog: ASP.NET MVC 2 Templates, Part 1: Introduction.
The model expressions are simple helpers which operate on the current model. The line DisplayForModel() is equivalent to DisplayFor(model => model).
TL;DR the same idea can be assumed for EditorFor(model => model)
and EditorForModel()
; these helper methods achieve the same thing. EditorForModel()
assumes the model expression is the @model
that was passed to the view.
Take the following models and view for example:
public class Person
{
public string Name {get; set;}
public Address MailingAddress {get; set;}
}
public class Address
{
public String Street {get; set;}
public String City {get; set;}
public String State {get; set;}
}
Create.cshtml
:
@model MyNamespace.Models.Person
/* So, you need an Editor for the Person model? */
@Html.EditorForModel()
/*the above is equivalent to @Html.EditorFor(model => model) */
/* you need to specify the Address property that the editor accepts? */
@Html.EditorFor(model => model.MailingAddress)
You should use it when possible, but sometimes you will need the customizability of individual Html.EditorFor
uses.
As for why the built-in templates don't use it, that's mainly because they are silly in general, but also because, if I recall, they need to wrap elements (like table rows etc.) around each Html.EditorFor
.
@Html.EditorForModel() ?? And give up the fun of writing your own view? smile
Besides the fun, doing so as a habit is rather dicey. Consider the following common scenario - you have a bool variable say IsMale in your database in your customer table. Well obviously you don't want the default version (IsMale with a check-box) - you probably want something a bit more friendly, say a {select, Options .... , /select} tags, right? that's where the view really starts kicking in. That's the customization. Every view is a little different. You have the RAZOR engine, exploit it to the max! In your view you can override anything, or even manually type an entire chunk of HTML code of your own.
I have never used EditorFor and don't ever imagine using it in the future. EditorFor assumes it knows what you want. You know what happens when you assume something.
Maybe if you were doing a quick Mvc spike to test something else you might use EditorFor.