Reputation: 91
I'm currently wetting my feet with ASP.NET MVC 3 w/ Razor, and I'm a bit confused about the most appropriate way to render HTML input elements.
As I see it, there are 3 methods to render those elements for a Model's property:
What is the recommended method for doing that? I'm a bit concerned with the EditorFor method, since I don't have any control over the rendered HTML, and I thought one of the mail goals of the MVC framework was to avoid the over-abstraction of WebForms.
What do you think? What is the best practice for this?
Thanks!
Upvotes: 9
Views: 2790
Reputation: 1028
The best way is HTML.EditorFor
, as you can create the editor templates for the given type and also your form will bind to your ModelView object authematically on form submit.
Upvotes: 0
Reputation: 5081
You actually do have control over the HTML generated by EditorFor: you can create custom templates for each type.
EditorFor has some distinct advantages when you want to do something more complicated then just a textbox. I've got a case where I want an editor for the "staff" property. So my EditorFor template creates a dropdown with the staff list in it, selects the right one, and then also adds a textbox with some Javascript used to filter the list by last name (as it's fairly lengthy). I could do that manually, but why? My view just calls EditorFor(whatever) and the template gets called. The code is very clean as a result.
So my advice is to use EditorFor unless you have a specific case where it makes sense not to do so. If you decide to customize your editors later, all you have to do is change the template for the type and voila! A good example is for dates. The basic EditorFor is just a textbox, but it's pretty easy to make a custom template that hooks up a jQuery date picker. You can do that later without having to change any of your views to take advantage of it if you're using EditorFor, which you can't do if you're doing it all inline with HTML textboxes.
Upvotes: 1
Reputation: 1038710
Html.EditorFor
is the preferred way. You can control the HTML by writing custom editor templates for the given type. ModelMetadata allows you to control the type of the generated input field. If you need to apply additional custom attributes you could also write a custom metadata provider.
Upvotes: 5