c# .net Adsense ADO.NET Linq Viruses/security asp.net MVC JQuery Angular-js Node-js SEO Java C++ SQL API Networking vb.net .Net Css JavaScript Generics c#.Net entity framework HTML Website host Website Construction Guide HTTP tutorial W3C tutorial Web Services JSON Psychology Ionic framework Angular ReactJS Python Computer Android
asp.net MVC

How to get modelstate errors in json c#?

| | MVC , web

In this tutorial I am going show you how to handle modelstate errors in json c#. Here I am using MVC5 and entity framework.You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element.

You have to define validations inside the class as per requirement. Here I have written for password match and minimum character required.

 

   public class ChangePasswordViewModel
    {
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }
 
        [DataType(DataType.Password)]
       [Display(Name = "Confirm new password")]
        [Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }


To display modelstate errors in view:

Ajax jQuery function call:

 You can return mvc model state errors via ajax JQuery function call, 

            $("#changepassword-form").submit(function (e) {
                e.preventDefault(); // <-- prevents the form from submitting
                    $.ajax({
                        url: "@Url.Action("ChangePassword", "Home")",
                        type: "POST",
                        async: false,
                        data: $(this).serialize(),
                        dataType: "json",
                        success: function (data) {
                            $("#lblcpStatus").html(data.message);
                            return false;
                        },
                        error: function (err) {
                            alert(err.statusText);
                        }
                    });
                    return false;
            });

 

Return Json to view:

 

[HttpPost]
        public ActionResult ChangePassword(ChangePasswordViewModel model)
        {
            Htmlinfo htmlinfo = new Htmlinfo();
            if (!ModelState.IsValid)
            {
                var message = string.Join(" | ", ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage));
                htmlinfo.message = message;
            }
            else
            {
                UserLogin user = HtmlUtility.GetUserData(User.Identity.Name);
                if (user != null)
                {
                    user.Password = HtmlUtility.Encrypt(model.NewPassword);
                    db.Entry(user).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                    htmlinfo.message = "Password changed successfully.";
                }
                else
                {
                    htmlinfo.message = "user does not exist.";
                }
            }
            return Json(htmlinfo, JsonRequestBehavior.AllowGet);
        }

 

This below video explains in detail about return mvc modelstate errors via ajax.