ASP. net mvc traverses the error message of ModelState, mvcmodelstate

Source: Internet
Author: User

ASP. net mvc traverses the error message of ModelState, mvcmodelstate

In ASP. net mvc, ModelState contains an error message indicating a verification failure, which is stored in the ModelState. Values [I]. Errors [j]. ErrorMessage attribute. Of course, by hitting a breakpoint, one-step debugging can view the specific verification failure error information, but sometimes you want to traverse the verification Failure Information in ModelState.

 

The ModelState type is ModelStateDictionary, and ModelStateDictionary is a dictionary set. The key is each attribute of the model, and the value is the ModelState corresponding to each attribute of the model.

 

The Errors attribute of ModelState stores all verification failure information, which is a ModelErrorCollection type. ModelErrorCollection is a set of modelerrors, And the ErrorMessage attribute of ModelError contains verification failure error information.

 

This is roughly the case:

 

○ ModelStateDictionary is actually an IDictionary <string, ModelState> type.
○ The ModelState. Errors attribute is actually of the ModelErrorCollection type.
○ ModelErrorCollection is actually an ICollection <ModelError> type.
○ ModelError. ErrorMessage stores all verification failure information.

 

How can I display the verification Failure Information?

 

{"Attribute 1", "attribute 1 Verification Failed error message 1 "},
{"Attribute 1", "attribute 1 Verification Failed error message 2 "},
{"Attribute 2", "attribute 2 Verification failure error message 1 "}
......

 

If you want to write it as above, you can read it in json and traverse it in the background.

 

Abstract A model that displays error information.

 

    public class ShowError
    {
        public ShowError(string key, string message)
        {
            Key = key;
            Message = message;
        }
        public string Key { get; set; }
        public string Message { get; set; }
    }

 

Because ModelState is of the ModelStateDictionary type, write an extension method for the ModelStateDictionary type. It reads the verification Failure Information in ModelStateDictionary along with the corresponding attributes, injects it into the ShowError model, and finally obtains an IEnumerable <ShowError> set.

 

   public static class ModelStateExtensions
    {
        public static IEnumerable<ShowError> AllModelStateErrors(this ModelStateDictionary modelState)
        {
            var result = new List<ShowError>();
// Locate the error field and error message
            var errorFieldsAndMsgs = modelState.Where(m => m.Value.Errors.Any())
                .Select(x => new {x.Key, x.Value.Errors});
            foreach (var item in errorFieldsAndMsgs)
            {
// Obtain the key
                var fieldKey = item.Key;
// Get the error message corresponding to the key
                var fieldErrors = item.Errors
                    .Select(e => new ShowError(fieldKey, e.ErrorMessage));
                result.AddRange(fieldErrors);
            }
            return result;
        }
    }

 

Then, a view model is used to test the validation failure error message.

 

   public class Student
    {
        public int Id { get; set; }
[Required (ErrorMessage = "Required")]
[StringLength (5, ErrorMessage = "1-5 characters in length")]
        public string Name { get; set; }
[Required (ErrorMessage = "Required")]
        public int Age { get; set; }
[Required (ErrorMessage = "Required")]
[Range (typeof (Decimal), "0", "100", ErrorMessage = "{0} must be between {1} and {2}.")]
        public decimal Score { get; set; }
    }

 

In HomeController, an Action is used to display the Student's strong view page, an Action is used to return all attributes obtained from ModelState and corresponding verification failure information to the foreground view in json format.

 

   public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new Student());
        }
        [HttpPost]
        public ActionResult GetErrors(Student student)
        {
            if (ModelState.IsValid)
            {
Return Content ("no error message ~~ ");
            }
            Response.StatusCode = 400;
            Response.TrySkipIisCustomErrors = true;
            var modelErrors = ModelState.AllModelStateErrors();
            return Json(modelErrors);
        }
    }        

 

In the Home/Index. cshtml view, when you click "Submit", the verification failure information is displayed on the console.

 

@model MvcApplication1.Models.Student
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("GetErrors", "Home", FormMethod.Post, new {id = "addForm"}))
{
    @Html.TextBoxFor(m => m.Name)
    <br />
    @Html.TextBoxFor(m => m.Age)
    <br />
    @Html.TextBoxFor(m => m.Score)
    <br />
<Input type = "button" id = "up" value = "Submit"/>
}
@section scripts
{
    <script type="text/javascript">
        $(function () {
            $('#up').on('click', function () {
                $.post('@Url.Action("GetErrors")', $('#addForm').serialize()).fail(function(error) {
                    var response = JSON.parse(error.responseText);
                    for (var i = 0; i < response.length; i++) {
                        var e = response[i];
                        var fieldKey = e.Key;
                        var message = e.Message;
                        console.log(fieldKey + ': ' + message);
                    }
                });
              
            });
        });
    </script>
}

 

Finally, the verification failure information is displayed in the console as follows:

 

Related Article

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.