Perhaps someone has already asked this. I am new to ajax and would need assistance in handling and linking ajax jquery with MVC ModelState.AddModelError. I would like the message in ModelState.AddModelError to be displayed as an alert in the error or success function of ajax jquery. As a background, the general method is that once the controller is called, it will return a PartialView to the ajax jquery to display in a particular <div>. If there is an error, the message should be displayed as an alert and there should be no change to whatever is currently displayed.
Below is a sample simple controller (HttpPost) and the ajax jquery routine.
Controller:
[Authorize]
[HttpPost]
public PartialViewResult Add()
{
int currentUser = (int)WebSecurity.CurrentUserId;
Book myBook = new Book();
myBook.GetChapter(currentUser, "Draft");
if (myBook.Chapters.Count() > 3)
{
ModelState.AddModelError("", "Too many chapters.");
}
return PartialView(myBook);
}The ajax call to post:
function submitaddbook() {$.ajax({
url: '@Url.Action("Add", "Book")',
type: "Post",
data: $('#addchapter').serialize(),
success: function (data) {$("#notes").html(data);
},
error: function (data) {
alert(data.errormessage);
}
});
}