In an ASP.NET MVC 4 application I have a view model that contains a nullable TimeSpan
property:
[DisplayName("My time")]
public TimeSpan? MyTime { get; set; }
It is bound to an input element in the view:
@Html.EditorFor(model => model.MyTime)
The input box gets rendered with the help of a custom editor template TimeSpan.cshtml
:
@model Nullable<System.TimeSpan>
@Html.TextBox("", (Model.HasValue
? Model.Value.ToString(@"hh\:mm") : string.Empty),
new { @class = "text-box single-line hasTimepicker" data_timepicker = true })
Now, if I enter the following two kinds of invalid times and submit the page I get the following different behaviour of the model binder:
If I enter a letter, say
"a"
into the input element theModelError
for this property when I drill into theModelState.Values
collection has theErrorMessage
property set to a message ("The value \"a\" for \"My time\" is invalid."
) and theException
property isnull
. The bound value ofMyTime
isnull
.This
ErrorMessage
is displayed in the validation summary of the page.If I enter an invalid time, say
"25:12"
, into the input element theModelError
for this property has theErrorMessage
property set to an empty string but theException
property set to an exception of typeInvalidOperationException
with an inner exception of typeOverflowException
telling me thatTimeSpan
could not be analysed because one of its numeric components is out of valid range. The bound value ofMyTime
isnull
.Again, the
ErrorMessage
is displayed in the validation summary of the page. But because it is empty it's not very useful.
Ideally for the second case of invalid input I would prefer to have the same kind of error message like for the first case, for example "The value \"25:12\" for \"My time\" is invalid."
.
How can I solve this problem?
Edit
A custom validation attribute apparently doesn't help here because it is not called for the invalid input in the examples above when already the model binder detects invalid values. I had tried that approach without success.