Shea Daniels
Shea Daniels

Reputation: 3270

How do I apply date formatting and add attributes to a textbox in MVC3?

In my application, I want all dates to display in the MM/DD/YYYY format and I also want the text box to be limited to 10 characters and have a certain class applied to it.

To that end, I made a custom editor template for Date that looks like this:

@ModelType System.Nullable(Of DateTime)

@Html.TextBoxFor(Function(d) d, New With {.class="polkDate", .maxlength="10"})

Then in my view I just can just call @Html.EditorFor(Function(m) m.someDate) and this works pretty well. However, because I'm using TextBoxFor, it doesn't respect the DisplayFormat attribute that's applied to my model class (i.e. it's spitting out the time as well instead of formatting the date).

I would love to use EditorFor so that it would respect the formatting that I want, but you can't add attributes like class and maxlength. I also tried just using the plain old TextBox helper, but I don't know how to make it generate the correct ID so that model binding still works.

Anybody know a way to make this happen? I don't feel like what I want to do here is too outlandish.

Upvotes: 0

Views: 832

Answers (1)

Shea Daniels
Shea Daniels

Reputation: 3270

This appears to do the trick:

@ModelType Date

@If Date.MinValue.Equals(Model) Then
    @Html.TextBox("", Nothing, New With {.class="polkDate", .maxlength="10"})
Else
    @Html.TextBox("", Model.ToShortDateString(), New With {.class="polkDate", .maxlength="10"})
End If

Looks like the framework automatically assigns the ID and name fields of the html input tag so everything works properly.

Upvotes: 1

Related Questions