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.
Post your comments / questions
Recent Article
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
- The request was aborted: Could not create SSL/TLS secure channel -Error in Asp.net
- FieldError: Cannot resolve keyword 'id' into field in Django project
Related Article