How can I return custom validation messages using JsonResult and AJAX?
Here is my controller action to add a student in StudentDB.
UPDATED:
[HttpPost()]
public ActionResult AddStudent(string studentName, int studentId)
{
var studentPresent = studentTable.Students.Where(s => s.StudentID == studentId&& b.StudentName == studentName);
if (studentPresent == null || !studentPresent .Any())
{
var student = new Student()
{
StudentName = studnetName,
StudentID = studentId,
};
studentTable.AddObject("Student", student);
studentTable.SaveChanges();
}
return new JsonResult();
}
Here is my JavaScript:
function addStudent() {
$.ajax({
type: 'POST',
url: '/StudentAdmin/AddStudent',
data: {
studentName: $('#studentName').val(),
studentNumber: GetTextBoxValue('#studentNumber'),
},
success: function (result) {
if ($('#studentPresent').val() == null) {
showMessage('Success', 'Student saved successfully.', '', false);
} else {
showMessage('Error', 'Student already present in database.', '', false);
}
GetGrid('#studentGrid').ajaxRequest();
hideForm();
},
studentPresent: function (result) {
showMessage('Error', 'Student Already present in Database.', '', true);
}
});
}
I want to display the “error” message if this student is already present in database.
Also, Is there a way of passing more validation messages to JasonResult?
Thanks in advance.
You can pass any object to the
JsonResultobject and it will be serialized (or it will attempt to serialize) down to the javascript.That results in a JSON object like so:
Being rendered to your javascript in the
resultvariable.Your code above actually doesn’t show any error message being generated; you would need a try / catch block if you want to get the text of the SQL exception.
EDIT:
You would have code like so:
And then in javascript, your callback is like so: