标签:
上次使用C#扩展方法,对HtmlHelper进行扩展。但是Html.ValidationMessageFor并没有对日期非空验证提示。
查看源码的时候发现对比自己生成的input,多了data-val这些属性。那么只需要在生成input的时候加上该属性即可。
var vas = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata);
tagBuilder.MergeAttributes(vas);
完整代码如下:
public static MvcHtmlString CalendarFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { TagBuilder tagBuilder = new TagBuilder("input"); ModelMetadata metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData); string name = ExpressionHelper.GetExpressionText(expression); htmlHelper.ValidateFor(expression); tagBuilder.MergeAttribute("name", name); tagBuilder.GenerateId(name); tagBuilder.MergeAttribute("type", "text"); //核心代码,直接通过这个方法可以获取属性上的验证信息,如:“data-val= ....”。 var vas = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata); //string类型,看有没长度限制,如果有,增加maxlength,minlength if (metadata.ModelType == typeof(string)) { var len = metadata.ContainerType.GetProperty(name).GetCustomAttribute(typeof(StringLengthAttribute)); if (len != null) { var stringlength = (StringLengthAttribute)len; if (stringlength.MaximumLength > 0) { tagBuilder.MergeAttribute("maxlength", stringlength.MaximumLength.ToString()); } if (stringlength.MinimumLength > 0) { tagBuilder.MergeAttribute("minlength", stringlength.MinimumLength.ToString()); } } } //如果model值不为,null,进行赋值。 if (metadata.Model != null) { tagBuilder.MergeAttribute("value", metadata.Model.ToString()); } tagBuilder.MergeAttributes(vas); tagBuilder.MergeAttribute("class", "Wdate"); tagBuilder.MergeAttribute("onclick", "WdatePicker({el:‘" + name + "‘})"); return new MvcHtmlString(tagBuilder.ToString()); }
这样大功告成。
MVC中My97date无法进行ValidationMessage修改
标签:
原文地址:http://www.cnblogs.com/GallopingSnail/p/5916234.html