回到目录
MVC4.0推出后,在模型验证上有了一个新的改近,它支持前端验证,即在用户POST之前,如果验证失败,则Action(POST方式的)不会被执行,而直接停留在原视图,这对于用户体验是好的,它就类似于ajax验证一样,不会将原页重定向。
MVC4.0在view中引用了jqueryval文件后,即可实现客户端实时验证
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
如果你不需要走JS方式验证,还是使用原来的POST方法后再进行验证的话,把上面那行删除即可,当然,MVC为我们提供的验证展示可能不是我们想要的,它往往会将“验证失败的提示信息”添加一个<span>然后为它加class,这可能并不是我们想要的,因为我们
的“错误提示”往往由前端开发人员提供的,所以,我们最需要的是“纯文字”的错误提示,现在,我把MVC的ValidationMessageFor扩展方法进行了新的扩展,我叫它ValidationMessageTextFor,它会将模型里的某个字段的验证错误的消息进行“纯文字”的输出,不
会有任何HTML标记,这才是我们所需要的,它也有不足,那就是目前并不支持前端实时模型验证!
ValidationMessageTextFor原代码如下,供大家学习与研究:
namespace System.Web.Mvc.Html { /// <summary> /// MVC中对HtmlHelper扩展方法 /// </summary> public static class MvcHtmlExtensions { /// <summary> /// 从ModelState中返回指定键对应的验证的错误消息 /// </summary> /// <typeparam name="TModel"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="htmlHelper"></param> /// <param name="expression"></param> /// <returns></returns> public static MvcHtmlString ValidationMessageTextFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { var fieldName = ExpressionHelper.GetExpressionText(expression); var modelState = htmlHelper.ViewData.ModelState; if (!modelState.Keys.Contains(fieldName)) return null; if (modelState[fieldName].Errors.Count == 0) return null; IList<string> errList = new List<string>(); modelState[fieldName].Errors.ToList().ForEach(i => { errList.Add(i.ErrorMessage); }); return MvcHtmlString.Create(string.Join(",", errList)); } } }
现在输出的错误消息就是纯文字,如图
QQ1s/nlyctJcbvoDTHHwGghujWsg3UuzITL3DkBszy8K5azZOf3TGliHLwq1jm325xGgUPNfDbTSOuVP96UGAPZo/hpY918N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