【问题标题】:How to get error back to ajax request如何将错误返回给ajax请求
【发布时间】:2015-04-30 13:46:03
【问题描述】:

我有一个从 ajax 调用的 WebMethod - 如果抛出错误,如果类型不是字符串/int 等,我如何将它返回给 ajax 请求?

[WebMethod]
public static List<SchedulerResource> getResourcesOnCall(Guid instructionID, bool ignorePostcode, int pageIndex, int pageSize)
{
    int totalRows = 0;
    List<SchedulerResource> schedulerResourceDS = null;

    try
    { 
        schedulerResourceDS = NewJobBLL.GetResourcesOnCall(instructionID, ignorePostcode, pageIndex, pageSize, ref totalRows);

        return schedulerResourceDS;
    }
    catch (Exception ex)
    {
        // what do I send back here?
    }

    return schedulerResourceDS;
}

这是我的 ajax - 我希望 .fail 能够处理异常 ex:

var requestResource = $.ajax({
    type: "POST",
    url: "NewJob.aspx/getResourcesDayShift",
    data: JSON.stringify(objResource),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
});

requestResource.done(function (data) {
    if (data.d.length == 0) {
        $("#lblEngineersDayShift").text("There are no Engineers available!");
    }
    else {
        loadTableDS(data);
    }
});

requestResource.fail(function (jqXHR, textStatus, errorThrown) {
    alert('loading of Engineers failed!' + jqXHR.responseText);
});

编辑:我不认为它是重复的 - 如果它的类型是 List,我正在询问如何从我的 WebMethod 返回 statusCode (int) 或 statusText (string)。因此我收到以下错误:

无法将类型“System.Net.HttpStatusCode”隐式转换为“System.Collections.Generic.List”

catch (WebException ex)
{
    var statusCode = ((HttpWebResponse)ex.Response).StatusCode;

    return statusCode;
}

【问题讨论】:

    标签: c# jquery asp.net ajax


    【解决方案1】:

    你可以让方法返回object 而不是List&lt;SchedulerResource&gt; 或尝试将 JSON 字符串返回给客户端。这样您就可以灵活地选择要返回的内容。

    一个很好的例子可以找到here

    对于将对象序列化为 JSON,您可以使用 JavaScriptSerializer

    我不使用 ASP.NET,但在 ASP.NET MVC 中,这看起来像这样: 你可以让你的方法返回JsonResult 而不是List&lt;SchedulerResource&gt;

    return Json(schedulerResourceDS, JsonRequestBehavior.AllowGet);
    

    然后如果发生错误可以返回

    Response.StatusCode = 500;
    return Json(new {error = ex.Message}, JsonRequestBehavior.AllowGet);
    

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多