jQuery Validate, ASP.NET MVC ModelState Errors (Async POST)

前端 未结 4 1540
遥遥无期
遥遥无期 2021-01-30 07:29

I\'m developing a web app with asp.net mvc 3 and I have some form that POST to an async action (via ajax). This action recives a ViewModel with some data annotations to validate

4条回答
  •  生来不讨喜
    2021-01-30 07:58

    Create a class to represent ModelState Errors for individual properties.

    public class ValidationError
    {
    
        public string PropertyName = "";
        public string[] ErrorList = null;
    }
    

    Create A Method which returns a List of ValidationErrors based on the ModelState

        public IEnumerable GetModelStateErrors(ModelStateDictionary modelState)
        {
            var errors = (from m in modelState
                                where m.Value.Errors.Count() > 0
                                select
                                   new ValidationError
                                   {
                                       PropertyName = m.Key,
                                       ErrorList = (from msg in m.Value.Errors
                                                      select msg.ErrorMessage).ToArray()
                                   })
                                .AsEnumerable();
            return errors;
        }
    

    Then in your controller Post Method do:

            if (!ModelState.IsValid)
            {
                return Json(new
                {
                    errors = true,
                    errorList = GetModelStateErrors(ModelState)
                }, JsonRequestBehavior.AllowGet);
            }
    

    You can create a JS Functions that loops through the error list returned above

    $.ajax({
                cache: false,
                async: true,
                type: "POST",
                url: form.attr('action'),
                data: form.serialize(),
                success: function (data) {
                    if (data.errors) {
                        displayValidationErrors(data.errorList);
                     }
                },
            error: function (result) {
                console.log("Error");
            }
    
        });
    
    function displayValidationErrors(errors) {
        $.each(errors, function (idx, validationError) {
    
            $("span[data-valmsg-for='" + validationError.PropertyName + "']").text(validationError. ErrorList[0]);
    
        });
    }
    

    In the example above I am only getting the first error message from 'ErrorList'. You can create an additional loop to get all the messages and append to your validation span.

提交回复
热议问题