3

I have the following model property

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d/M/yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date of Screening")]
public DateTime? ScreeningDate { get; set; }

and the following view:

@Html.TextBoxFor(model => model.ScreeningDate, new { @class="date maintainState" })

and yet I get this markup for the textbox:

 <input value="18/06/2013 12:00:00 AM" class="date maintainState" ... type="text"  />

I want the value to be 18/06/2013

It works when I apply @Html.EditorFor, but I need control over the class attribute. What am I doing wrong? Thank you very much.

Brent
  • 4,611
  • 4
  • 38
  • 55

1 Answers1

3

It works when I apply @Html.EditorFor, but I need control over the class attribute. What am I doing wrong?

Nothing, it's how things work. Only the EditorFor and DisplayFor helpers respect the [DisplayFormat] attribute.

I understand that you are using TextBoxFor because you want to apply a custom class to the field which is what the EditorFor doesn't allow you to. But that's not true. All that the EditorFor helper does is to render the corresponding editor template. And if you do not have a custom template it renders the default one.

So what?

Well, you write a custom editor template for the DateTime type that will behave as you want. Just like that in ~/Views/Shared/EditorTemplates/DateTime.cshtml:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData)

And then simply:

@Html.EditorFor(model => model.ScreeningDate, new { @class="date maintainState" })

Now killed 2 rabbits with one bullet:

  • We applied the desired format
  • We applied the desired class to the input field

And if you wanna kill a third rabbit and be able to validate this custom format when the form is submitted back (because remember that the default model binder doesn't care much about this [DisplayFormat] attribute) you could write a custom model binder that will respect the [DisplayFormat] attribute, just as I explained here: https://stackoverflow.com/a/7836093/29407

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928