Traversing error messages stored in the Modelstate

Source: Internet
Author: User

In server-side validation, sometimes we add a modelerror, and then we need to return that information to the client as JS. Such as:

[HttpPost]        Public ActionResult Index (Logonmodel model)        {            if (string. IsNullOrEmpty (model. UserName)            {                modelstate.addmodelerror ("UserName", "Please enter the user name. ");                Return JavaScript ("alert (' Please enter username ')");            }            if (string. IsNullOrEmpty (model. PassWord)            {                modelstate.addmodelerror ("UserName", "Please enter a password. ");                Return JavaScript ("alert (' Please enter password ')");            }            if (string. IsNullOrEmpty (model. Checkcode)            {                modelstate.addmodelerror ("UserName", "Please enter the verification code. ");                Return JavaScript ("alert (' Please enter a verification code ')");            }            if (modelstate.isvalid)            {                Response.Write ("asdf");            }            return View ();        }

It is possible to rewrite this again, but it does the repetitive work, and if we can get the error message added in the Modelstate, we can save a lot of work.

The modelstate itself is a dictionary and stores information about validation failures. Specifically stored in modelstate.values[i]. ERRORS[J]. The ErrorMessage property.

The Errors property of Modelstate stores all validation failure information, is a modelerrorcollection type, Modelerrorcollection is a collection of Modelerror, The ErrorMessage property of Modelerror contains a validation failure error message.

This is roughly the case:

0ModelStateDictionary is actually idictionary<string, modelstate> type
The 0modelstate.errors property is actually a modelerrorcollection type
0ModelErrorCollection is actually a icollection<modelerror> type
The 0modelerror.errormessage property stores all validation failure information

The next task, in fact, is how to find out the verification information. We'll add a validation message by hand and try to display it:

Modelstate.addmodelerror ("UserName", "Please enter a user name.") "); return JavaScript (" alert (' "+ ModelState.Values.First ().) Errors[0]. ErrorMessage + "')");

In the above code, the values collection represents different key values, while errors represents different information under the same key value.

Modelstate.addmodelerror ("UserName", "Please enter a user name.") "); Modelstate.addmodelerror ("UserName", "User name is not correct.") "); Modelstate.addmodelerror ("PassWord", "Please enter the password.") "); Modelstate.addmodelerror ("PassWord", "Password is incorrect.") ");//outputs the first return Content (ModelState.Values.First (). Errors[0]. errormessage);//Output The second return Content (ModelState.Values.First (). ERRORS[1]. errormessage);//output Third return Content (ModelState.Values.Skip (1). First (). Errors[0]. errormessage);//output Fourth return Content (ModelState.Values.Skip (1). First (). ERRORS[1]. ErrorMessage);

Clearly, it is not difficult to traverse a modelstate.

                StringBuilder errinfo = new StringBuilder ();                foreach (var s in modelstate.values)                {                    foreach (var p in s.errors)                    {                        errinfo. AppendFormat ("{0}\\n", p.errormessage);                    }                }                Return JavaScript ("alert ('" + errinfo. ToString () + "')");

The following are the code that displays the error message centrally and displays the error message in turn:

Centralized display of error messages:

 [HttpPost] public actionresult Index (Logonmodel model) {if (string. IsNullOrEmpty (model. UserName) {modelstate.addmodelerror ("UserName", "Please enter the user name.            "); } if (string. IsNullOrEmpty (model. PassWord) {modelstate.addmodelerror ("PassWord", "Please enter a password.            "); } if (string. IsNullOrEmpty (model. Checkcode) {modelstate.addmodelerror ("Chkcode", "Please enter the verification code.            "); } if (!                Modelstate.isvalid) {StringBuilder errinfo = new StringBuilder ();                        foreach (var s in modelstate.values) {foreach (var p in s.errors) { Errinfo.                    AppendFormat ("{0}\\n", p.errormessage); }} return JavaScript ("alert ('" + errinfo.            ToString () + "')");        } return View (); }

Display the error message in turn:

[HttpPost]        Public ActionResult Index (Logonmodel model)        {            if (string. IsNullOrEmpty (model. UserName)            {                modelstate.addmodelerror ("UserName", "Please enter the user name. ");                Return JavaScript ("alert ('" + ModelState.Values.First ().) Errors[0]. ErrorMessage + "')");            }            if (string. IsNullOrEmpty (model. PassWord)            {                modelstate.addmodelerror ("UserName", "Please enter a password. ");                Return JavaScript ("alert ('" + ModelState.Values.First ().) Errors[0]. ErrorMessage + "')");            }            if (string. IsNullOrEmpty (model. Checkcode)            {                modelstate.addmodelerror ("UserName", "Please enter the verification code. ");                Return JavaScript ("alert ('" + ModelState.Values.First ().) Errors[0]. ErrorMessage + "')");            }            if (modelstate.isvalid)            {                            }            return View ();        }

Traversing error messages stored in the Modelstate

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.