Search code examples
c#jsonajaxwebmethod

How is the best way to return an error to ajax request?


When one WebMethod it's called from ajax, if I return a simple string, the ajax code go to success method without errors, something like this:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string Hello()
{
    return "Hello World";
}

This is right, but, how is the correct way to make the WebMethod for return a error and this will be captured in ajax Error method instead of success method?

Thanks


Solution

  • Change your Response status Code :

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string Hello()
    {
        Response.StatusCode = 400 ; // Will be captured on ajax error method 
        return "Hello World";
    }