Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom EditorTemplate not being used in MVC4 for DataType.Date

I'm upgrading an MVC3 application to MVC4 using the instructions from Microsoft. Everything went fairly smoothly - except a few of my date model properties are now rendering differently. For example, one of these properties is defined in the viewmodel like this:

[Required(ErrorMessage = "Required")]
[DataType(DataType.Date)]
[RegularExpression(@"([1-9]|0[1-9]|1[012])...",
    ErrorMessage = "Format is mm/dd/yyyy")]
[FormatHint("mm/dd/yyyy")]
[InputSize("small")]
public string Date { get; set; }

Before upgrading to MVC4, this would be rendered via calling @Html.EditorFor(m => m.Date) which would use a custom EditorTemplate - the String.cshtml template (since it's a string!). I have some custom data annotations that formats the html so it utilizes a field layout, jQueryUI, and twitter Bootstrap on the client side. The validation is done via jquery validation unobtrusive. Anyhow, this is how it previously rendered:

date editor

Now that I'm using MVC4, the String.cshtml editor template is not being called for this property any longer. It renders like this (in Chrome using the HTML5 editor stuff, I assume):

date editor mvc4

The input element looks pretty much the same - all the jQuery validation bits are in there - the only difference seems to be the type attribute is now type="date", where before it was type="text".

I'd like to continue using the String.cshtml EditorTemplate for this datatype. I'm thinking there might be a data annotation that I can put on the ViewModel property to provide a TemplateHint for @Html.EditorFor(...). If not this, I'd like to know the custom EditorTemplate that I can write to hijack MVC4's formatting (I've already tried DateTime.cshtml - it's not being called either). If not either of those, then I'm open to suggestions on how to get my property rendering like it used to.

like image 591
James Kolpack Avatar asked Dec 08 '22 18:12

James Kolpack


1 Answers

In MVC4, the used template is determinated from :

  1. The UIHintAttribute if any
  2. The DataTypeAttribute if any
  3. The type of the property

In MVC3, the DataTypeAttribute was not used.

Your property has a

[DataType(DataType.Date)]

so the template Date.cshtml is used. If it does not exists, default rendering is executed.

You have two options to resolve your problem :

  1. Add a UIHint("String") on your property, or
  2. Rename your editor template from String.cshtml to Date.cshtml
like image 104
gentiane Avatar answered Dec 11 '22 07:12

gentiane