EditorFor() and html properties
Asp.Net MVC 2.0 preview builds provide helpers like
Html.EditorFor(c => c.propertyname)
If the property name is string, the above code renders a texbox.
What if I want to pass in MaxLength and Size properties to the text box or my own css class property?
Do I need to create one template for each size and length combinations in my application? If so, that doesn't make the default templates that usable.
Solution 1:
In MVC3, you can set width as follows:
@Html.TextBoxFor(c => c.PropertyName, new { style = "width: 500px;" })
Solution 2:
I solved this by creating an EditorTemplate named String.ascx in my /Views/Shared/EditorTemplates folder:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<% int size = 10;
int maxLength = 100;
if (ViewData["size"] != null)
{
size = (int)ViewData["size"];
}
if (ViewData["maxLength"] != null)
{
maxLength = (int)ViewData["maxLength"];
}
%>
<%= Html.TextBox("", Model, new { Size=size, MaxLength=maxLength }) %>
In my view, I use
<%= Html.EditorFor(model => model.SomeStringToBeEdited, new { size = 15, maxLength = 10 }) %>
Works like a charm for me!
Solution 3:
None of the answers in this or any other thread on setting HTML attributes for @Html.EditorFor were much help to me. However, I did find a great answer at
Styling an @Html.EditorFor helper
I used the same approach and it worked beautifully without writing a lot of extra code. Note that the id attribute of the html output of Html.EditorFor is set. The view code
<style type="text/css">
#dob
{
width:6em;
}
</style>
@using (Html.BeginForm())
{
Enter date:
@Html.EditorFor(m => m.DateOfBirth, null, "dob", null)
}
The model property with data annotation and date formatting as "dd MMM yyyy"
[Required(ErrorMessage= "Date of birth is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateOfBirth { get; set; }
Worked like a charm without writing a whole lot of extra code. This answer uses ASP.NET MVC 3 Razor C#.
Solution 4:
May want to look at Kiran Chand's Blog post, he uses custom metadata on the view model such as:
[HtmlProperties(Size = 5, MaxLength = 10)]
public string Title { get; set; }
This is combined with custom templates that make use of the metadata. A clean and simple approach in my opinion but I would like to see this common use case built-in to mvc.
Solution 5:
I'm surprised no one mentioned passing it in "additionalViewData" and reading it on the other side.
View (with line breaks, for clarity):
<%= Html.EditorFor(c => c.propertyname, new
{
htmlAttributes = new
{
@class = "myClass"
}
}
)%>
Editor template:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<string>" %>
<%= Html.TextBox("", Model, ViewData["htmlAttributes"])) %>