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!
EditorForModel(HtmlHelper, String) Returns an HTML input element for each property in the model, using the specified template. EditorForModel(HtmlHelper, String, Object) Returns an HTML input element for each property in the model, using the specified template and additional view data.
ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.
EditorFor<TModel,TValue>(HtmlHelper<TModel>, Expression<Func<TModel,TValue>>, String, String, Object) Returns an HTML input element for each property in the object that is represented by the expression, using the specified template, HTML field name, and additional view data.
Simply put, the Html. EditorFor method allows the developer to retain control over the display of form elements by data type (ie. string, boolean, int…etc) or model attribute at a global level rather than at an individual view level. This allows for cleaner ASP markup and easily scalable form controls.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With