如何使用 JsonResult 和 AJAX 返回自定义验证消息?
这是我在 StudentDB 中添加学生的控制器操作。
更新:
[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();
}
这是我的 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);
}
});
}
如果该学生已经存在于数据库中,我想显示“错误”消息。另外,有没有办法将更多验证消息传递给 JasonResult?
提前致谢。