How does one return an error in an aspx page method decorated with WebMethod
?
Sample Code
$.ajax({
type: "POST",
url: "./Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
[WebMethod]
public static string GetData()
{
}
How does one return error from a webmethod? So one can be able to use the jquery error portion to show the error detail.
I don't know if there's a more WebMethod
-specific way of doing it, but in ASP.NET you'd generally just set the status code for your Response object. Something like this:
Response.Clear();
Response.StatusCode = 500; // or whatever code is appropriate
Response.End;
Using standard error codes is the appropriate way to notify a consuming HTTP client of an error. Before ending the response you can also Response.Write()
any messages you want to send. The formats for those are much less standardized, so you can create your own. But as long as the status code accurately reflects the response then your JavaScript or any other client consuming that service will understand the error.
Just throw the exception in your PageMethod and catch it in AjaxFailed. Something like that:
function onAjaxFailed(error){
alert(error);
}
An error is indicated by the http status code (4xx - user request fault, 5xx - internal server fault) of the result page. I don't know asp.net, but I guess you have to throw an exception or something like that.