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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With