C# 自定义MVC帮助器ForModel和DataAnnotation

C# 自定义MVC帮助器ForModel和DataAnnotation,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我已经创建了一个DatePickerforHelper,但是它没有得到我的ViewModel的验证器 我的viewmodel: public class Dates { public DateTime ExpiringDate { get; set; } [Required(ErrorMessage = "This field is required!")] [LessThan("ExpiringDate")] public DateTime Start { g

我已经创建了一个DatePickerforHelper,但是它没有得到我的ViewModel的验证器

我的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());
    }
public static MvcHtmlString DatePickerFor(此HtmlHelper帮助程序,表达式/*,一些参数*/)
{
StringBuilder html=新的StringBuilder();
html.Append(“”);
html.Append(“”);
html.Append(“”);
html.Append(“”);
返回新的MvcHtmlString(html.ToString());
}
是否可以将viewmodel中定义的“data val required”和其他验证添加到我的html中


谢谢

您可以尝试覆盖默认的textboxforhelper,并使用自定义属性扩展输出

    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);
    }
public static MvcHtmlString日期选择器(此HtmlHelper、表达式表达式、对象htmlAttributes)
{
var extendedAttributes=HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
Add(“类”,“窗体控件日期选择器”);
添加(“数据日期格式”,“日/月/年”);
添加(“占位符”,“00/00/0000”);
返回htmlHelper.TextBoxFor(表达式,extendedAttributes);
}