1

I have a TimeSpan Model that I am trying to display in a View (@Html.EditorFor) with a masked format of mm:ss (duration measured in minutes and seconds). I DO NOT want/need hours or AM/PM, but my View without exception displays the mask = "--:-- --" which is the default format "hh:ss tt". I cannot get it to display ANY OTHER masked format. See below for Model and View. I have completely run out of ideas here. Please help!

Model:

[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:mm\\:ss}", ApplyFormatInEditMode = true)]
public TimeSpan? LengthAct { get; set; }

View:

@Html.EditorFor(m => m.LengthAct, new { htmlattributes = new { @class = "form-control", data_val = "true", data_val_required = "Length is required" } })
Sam
  • 11
  • 1
  • 5

2 Answers2

0

Maybe this can help you:

@Html.TextBoxFor(x => x.LengthAct, "{0:mm\\:ss}")

Greetings!!

Gonzalo Diaz
  • 139
  • 1
  • 8
0

If you apply DataType.Time to the property, and then render it with EditorFor, you're going to get an HTML5 time input. In supported browsers, this will often be presented to the user as a formatted control allowing you type the hours and minutes individually. At least if the browser is using an en-US local, the time will be 12-hour format, and there will be an AM/PM selector, as well. I'm not sure what browsers like Chrome display in other locales, as I haven't personally tried it. I'm assuming if the locale uses 24-hour time, you wouldn't have an AM/PM selector, but I'm just guessing.

Regardless, the point is that all the stuff you say you don't want is actually part of the browser's built in control. If you don't like it, your only real option is to use an input of type text. You'll need to either remove the DataType annotation (although that will affect validation of the field) or use Html.TextBoxFor instead of Html.EditorFor.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • If I remove `DataType.Time` will the annotation below apply a mask to the textboxfor? `[DisplayFormat(DataFormatString = "{0:mm\\:ss}", ApplyFormatInEditMode = true)]` – Sam Nov 24 '15 at 19:58
  • No, `DisplayFormat` doesn't have any effect on the input type used. However, now that I think about it, removing the `DataType` annotation might not work. `EditorFor` also considers the property type, and since you're dealing with a `TimeSpan`, it might still using the `time` type. The safest bet is to just use `TextBoxFor`, since that will always use the `text` type unless you pass a different type in the `htmlAttributes` param. – Chris Pratt Nov 24 '15 at 20:22
  • So then I lose the masking I was hoping for..Still confused. – Sam Nov 24 '15 at 20:58
  • You'll need to use `DisplayFormat` whichever path you take. – Chris Pratt Nov 30 '15 at 15:20