如何编写ajax函数来接收从控制器方法传回的返回码?

时间:2013-08-23 14:24:15

标签: jquery ajax asp.net-mvc

从ajax函数,我调用MVC控制器方法,如果方法失败则返回-1。如何编写ajax函数以接收-1以便我可以执行javascript警报?

function RejectButtonProcess()
{
    // This will execute the method in the specified controller. 
    $.ajax({
        type: "POST",
        url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
        error: function(XMLHttpRequest, textStatus, errorThrown)
        { 
           //alert("Status: " + textStatus); alert("Error: " + errorThrown); 
           alert("An error occurred during the reject process. Contact the IT department."); 
        }  
    });
}

3 个答案:

答案 0 :(得分:1)

添加成功回调:

    success: function (data, textStatus, jqXHR) {
        // process the data
    },

返回的data变量将包含返回代码(可能是JSON,具体取决于您设置端点的方式)。

答案 1 :(得分:0)

您可以按照以下方式执行此操作,

$.ajax({
    type: "POST",
    url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
    data: JSON.stringify(model), \\ Pass data if any
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if(result == -1) { \\Check Result
            alert("Error");
        }
    },
    error: function () {
    }
});

答案 2 :(得分:0)

虽然回送一个响应并检查回调中的数据对象(如上所述@Richard和@Jatin)会起作用,但我倾向于按照以下模式滚动我自己的AjaxResult对象,用模型保护这个对象状态有效性,成功状态,以及我需要传递回$ .ajax成功回调函数的任何数据。这为处理$ .ajax请求提供了灵活而优雅的解决方案。例如:

// custom ajax request result class
public class AjaxResult
{
    public bool IsValid { get; set; }
    public bool Success { get; set; }
    public string Message { get; set; }
    public Dictionary<string, object> Data { get; set; }

    public AjaxResult()
    {           
        Data = new Dictionary<string, object>();
    }

    public void AddData(string dataKey, object dataValue)
    {
        if (dataKey != null && !Data.ContainsKey(dataKey))
        {
            Data.Add(dataKey, dataValue);
        }
    }
}

// controller
public ActionResult NhpdAdminRejectAddress(NhpdAdminViewModel model)
{
    AjaxResult result = new AjaxResult();

    if (ModelState.IsValid)
    {
        // do something
        result.AddData("Code", -1);
        result.IsValid = true;
        result.Success = true;
    }

    return Json(result);
}

// ajax post request
$.ajax({
    type: "POST",
    url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
    data: JSON.stringify(model),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if (result != null && result.Data != null && result.Data.Code != null)
        {
            int code = result.Data.Code;
        }
    },
    error: function () {
        // handle error
    }
});