自定义MVC Helper ForModel和Dataannotations
本文关键字:Dataannotations ForModel Helper MVC 自定义 | 更新日期: 2023-09-27 18:27:39
我已经创建了一个DatePickerFor Helper,但它没有得到ViewModel的验证器。
我的视图模型:
public class Dates
{
public DateTime ExpiringDate { get; set; }
[Required(ErrorMessage = "This field is required!")]
[LessThan("ExpiringDate")]
public DateTime Start { get; set; }
}
我的助手:
public static MvcHtmlString DatePickerFor(this HtmlHelper helper,Expression<Func<TModel, TProperty>> expression /*, Some args*/)
{
StringBuilder html = new StringBuilder();
html.Append("<div class='"input-group'">");
html.Append("<span class='"input-group-addon'"><i class='"fa fa-calendar'"></i></span>");
html.Append("<input id='"" + id + "'" type='"text'" name='"" + name + "'" value='"" + dateValue + "'" class='"form-control datepicker " + cssClass + "'" data-dateformat='"dd/mm/yy'" placeholder='"00/00/0000'" " + attrs + "/>");
html.Append("</div>");
return new MvcHtmlString(html.ToString());
}
是否可以将视图模型中定义的"data val required"和其他验证添加到我的html中?
谢谢!
您可以尝试覆盖默认的TextBoxFor帮助程序,并使用自定义属性扩展输出
public static MvcHtmlString DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var extendedAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
extendedAttributes.Add("class", "form-control datepicker");
extendedAttributes.Add("data-dateformat", "dd/mm/yy");
extendedAttributes.Add("placeholder", "00/00/0000");
return htmlHelper.TextBoxFor(expression, extendedAttributes);
}