自定义MVC助手ForModel和Dataannotations

时间:2014-10-23 14:24:05

标签: c# asp.net-mvc-4

我已经创建了一个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());
    }

可以使用&#34; data-val-required&#34;以及在viewmodel中定义的其他验证添加到我的html?

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以尝试覆盖默认的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);
    }