leddy
leddy

Reputation: 553

How to get error back to ajax request

I have a WebMethod that I am calling from ajax - if an error is thrown, how do I get that back to the ajax request if the type is not a string/int etc?

[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;
}

And this is my ajax - I want the .fail to be able to process the exception 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);
});

EDIT: I don't think it is duplicate - I'm asking how to return the statusCode (int) or statusText (string) from my WebMethod if it's type is List< SchedulerResource >. Therefore I get the following error:

Cannot implicitly convert type 'System.Net.HttpStatusCode' to 'System.Collections.Generic.List'

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

    return statusCode;
}

Upvotes: 1

Views: 1658

Answers (1)

gyosifov
gyosifov

Reputation: 3223

You can make the method return object not List<SchedulerResource> or try returning a JSON string back to the client. That way you keep the flexibility to choose what to return.

A good example can be found here.

For the serialization of the object to JSON you can use JavaScriptSerializer

I don't use ASP.NET, but in ASP.NET MVC this would look something like this: You can make your method return JsonResult and not List<SchedulerResource>

return Json(schedulerResourceDS, JsonRequestBehavior.AllowGet);

Then if an error occurs you can return

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

Upvotes: 1

Related Questions