Back to Catalog
MVC4.0 introduced, a new approach to model validation, which supports front-end verification, that is, before the user post, if the validation fails, then the action (post mode) will not be executed, and directly stuck in the original view, which is good for the user experience, it is similar to Ajax validation, the original page will not be redirected.
MVC4.0 client Real-time validation after referencing the Jqueryval file in view
@section Scripts { @Scripts. Render ("~/bundles/jqueryval")}
If you do not need to go to the JS method to verify, or use the original post method after the verification, the above line can be deleted, of course, MVC provides us with the verification of the display may not be what we want, it will often "failed to verify the message" To add a <span> And then add class to it, which may not be what we want because we
"Error hints" are often provided by front-end developers, so what we need most is "plain text" error hints, and now, I'm going to extend MVC's validationmessagefor extension method to a new extension, I call it Validationmessagetextfor, it will make a "plain text" output of the validation error message for a field in the model, not
There will be any HTML tags, this is what we need, it is also insufficient, that is, the current front-end real-time model validation is not supported!
validationmessagetextfor The original code as follows, for everyone to learn and research:
namespacesystem.web.mvc.html{/// <summary> ///extension methods for HtmlHelper in MVC/// </summary> Public Static classmvchtmlextensions {/// <summary> ///returns the validation error message for the specified key from the Modelstate/// </summary> /// <typeparam name= "TModel" ></typeparam> /// <typeparam name= "Tproperty" ></typeparam> /// <param name= "HtmlHelper" ></param> /// <param name= "expression" ></param> /// <returns></returns> Public StaticMvchtmlstring Validationmessagetextfor<tmodel, Tproperty> ( ThisHtmlhelper<tmodel> HtmlHelper, Expression<func<tmodel, tproperty>>expression) { varFieldName =expressionhelper.getexpressiontext (expression); varModelstate =htmlHelper.ViewData.ModelState; if(!modelState.Keys.Contains (fieldName))return NULL; if(Modelstate[fieldname]. Errors.Count = =0) return NULL; IList<string> errlist =Newlist<string>(); Modelstate[fieldname]. Errors.tolist (). ForEach (i={errlist.add (i.errormessage); }); returnMvchtmlstring.create (string. Join (",", errlist)); } }}
Now the output error message is plain text,
Back to Catalog
Fall in love with MVC~MVC4 model validation can be placed on the front