I wrote my own HtmlHelper Extension Method to display a time-input.
public static MvcHtmlString TimePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
string expressionText = ExpressionHelper.GetExpressionText(expression);
string value = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model.ToString();
return TimePicker(htmlHelper, expressionText, value);
}
public static MvcHtmlString TimePicker(this HtmlHelper helper, string name, string value)
{
TagBuilder builder = new TagBuilder("input");
builder.MergeAttribute("type", "time");
builder.MergeAttribute("id", name);
builder.MergeAttribute("name", name);
if (value != null)
{
builder.MergeAttribute("value", value);
}
return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
}
This is how I use it:
@Html.TimePickerFor(model => model.StartTime)
When the time is not valid, I add an error like this:
ModelState.AddModelError("StartTime", "The selected time is already taken.");
When this error is added, it should add the input-validation-error class to the input, but it doesn't. I cannot get it to work. It does show the error in the ValidationSummary, and it adds the class to the default inputs. Any help would be appreciated!
I already tried adding it like this, but this still won't add the class:
var validation = helper.GetUnobtrusiveValidationAttributes(name);
foreach (KeyValuePair<string, Object> attribute in validation)
{
builder.MergeAttribute(attribute.Key, attribute.Value.ToString());
}
Edit: temporary workaround found, haven't been able to solve the problem though
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(name, out modelState))
{
if (modelState.Errors.Count > 0)
builder.AddCssClass("input-validation-error");
}