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
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article