我需要从控制器发送错误消息,如果在ajax函数中发生错误。 这是我的控制器代码:
//check if the day is already approved
string check1 = "SELECT approve_status_id FROM table_approvals WHERE approve_date=" + date + " AND user_id=" + Session["userID"];
MySqlCommand status_cmd = new MySqlCommand(check1, con);
MySqlDataReader rdrStatus = status_cmd.ExecuteReader();
while (rdrStatus.Read())
{
if (rdrStatus.GetString(0) == "5")
{
valid = false;
error = "You cannot edit already approved dates!";
response.Message = error;
return View(Json(new { success = false,error},JsonRequestBehavior.AllowGet));
}
}
我的ajax功能:
$.ajax({
url: '@Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function () {
window.location.href = '@Url.Action("Index", "AddLine")';
},
error: function () {
$.getJSON('/AddLine/SaveLine', function (json) {
alert('error');
$("#ajaxPostMessage").html(json.Message);
});
答案 0 :(得分:0)
将所有东西包裹在try catch中。您可以简单地调用JSON方法,该方法将创建JSON响应并将其返回给客户端代码。此外,当它是HttpPost
Action方法时,您不需要JsonRequestBehavior.AllowGet来返回JSON。您只需要GET
。($.getJSON, $.get ..
)
try
{
//code for getting data to reader
while (rdrStatus.Read())
{
if (rdrStatus.GetString(0) == "5")
{
valid = false;
var errorMsg = "You cannot edit already approved dates!";
return Json( new { success = false,Error=errorMsg });
}
}
}
catch(Exception ex)
{
//log Error
return Json(new { success = false,Error="Some Error!"});
}
这会将这样的JSON返回给客户端
{ "success ": "True", "Error": "SomeError" }
现在,在您的客户端代码中,您可以查看JSON
并执行任何操作。
success: function (data) {
if(data.success=="True")
{
window.location.href = '@Url.Action("Index", "AddLine")';
}
else
{
alert(data.Error);
}
},