0

我需要从控制器发送一条错误消息,以防 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);
        });
4

1 回答 1

0

将所有内容都包裹在 try catch 中。您可以简单地调用 JSON 方法,该方法将创建 JSON 响应并将其返回给客户端代码。HttpPost此外,当 JsonRequestBehavior.AllowGet 是Action 方法时,您不需要返回 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);
    }
},
于 2012-08-30T12:04:01.723 回答