Search code examples
asp.net-mvceditortemplates

ASP.NET MVC - How to add a Class to Html.EditorFor when classes already exist due to unobtrusive js validation?


I'm trying to add a Class to the EditorFor Helper inside an EditorTemplate.

The problem is that because I'm using Unobtrusive Validation, the input element already has classes assigned to it.

Here is my EditorTemplate

@Inherits System.Web.Mvc.ViewUserControl(Of Nullable(Of Date))
@Html.TextBox("", If(Model.HasValue, String.Format("{0:MM/dd/yyyy}"), String.Empty), New With {.class = "datepicker"})

And here is the output

<input class="text-box single-line" id="BirthDate" name="BirthDate" type="text" value="08/08/1980" />

You can see here that the datepicker class has not been added, yet the "value" has been properly formatted.

Basically I can see that the EditorTemplate is working, but the Class is not being appended to the rest of the classes on the <input> element.

Do any of you know how to fix this?


Solution

  • Turns out I had to add a <UIHint("Date")> to my Buddy Class.

    All is right again.

    @ModelType Date?
    @Html.TextBox("", If(Model.HasValue, String.Format("{0:MM/dd/yyyy}", Model), String.Empty), New With {.class = "datepicker"})
    

    Here's the reason for the UIHint.

    The default template name is based on the CLR type name, in this case DateTime. "Date" is a shortcut name in VB, not the real type name (much like "int" in C# is really a shortcut for CLR's "Int32").