我编写了自己的HtmlHelper扩展方法来显示时间输入。
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));
}
这就是我使用它的方式:
@Html.TimePickerFor(model => model.StartTime)
当时间无效时,我会添加如下错误:
ModelState.AddModelError("StartTime", "The selected time is already taken.");
添加此错误时,应将input-validation-error
类添加到输入中,但不会。我无法让它发挥作用。它确实显示ValidationSummary
中的错误,并将类添加到默认输入。任何帮助将不胜感激!
我已经尝试过像这样添加它,但是这仍然不会添加类:
var validation = helper.GetUnobtrusiveValidationAttributes(name);
foreach (KeyValuePair<string, Object> attribute in validation)
{
builder.MergeAttribute(attribute.Key, attribute.Value.ToString());
}
编辑:发现临时解决方法,虽然无法解决问题
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(name, out modelState))
{
if (modelState.Errors.Count > 0)
builder.AddCssClass("input-validation-error");
}
答案 0 :(得分:2)
你在做什么不是一种解决方法!这就是你应该怎么做的
string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
ModelState modelState;
if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState))
{
if (modelState.Errors.Count > 0)
{
builder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
}
}
GetUnobtrusiveValidationAttributes
的目的是将不显眼的验证属性返回到工作状态。这些属性以名称&#34; data-val&#34;开头。并由jquery.validate.unobtrusive.js
<input data-val="true" data-val-required="Please supply the title." id="Title" name="Title" type="time">
您的自定义帮助程序必须具有两者才能正常工作。
供参考,请阅读InputExtensions here
的源代码等等!
MVC实际上支持HTML5时间输入!你不需要自己写。
public class TestModel
{
[DataType(DataType.Time)]
public DateTime MyTime { get; set; }
}
@Html.EditorFor(model => model.MyTime)