0

从 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."); 
        }  
    });
}
4

3 回答 3

1

添加成功回调:

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

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

于 2013-08-23T14:25:50.467 回答
0

You can do it as follows,

$.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 () {
    }
});
于 2013-08-23T14:30:23.310 回答
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
    }
});
于 2013-08-23T20:47:33.817 回答