Jquery Ajax, return success/error from mvc.net controller

后端 未结 3 538
庸人自扰
庸人自扰 2020-12-07 23:52

I would like to control when to reply an error message and when a success message but I am always get the error message:

here is what I am trying to do:

3条回答
  •  旧时难觅i
    2020-12-08 00:34

    When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

    return StatusCode(500, "My error");
    

    Or

    return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
    

    Or

    Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    return Json(new { responseText = "my error" });
    

    Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

    you can have ajax call like:

    $.ajax({
            type: "POST",
            url: "/General/ContactRequestPartial",
            data: {
                HashId: id
            },
           success: function (response)  {
                console.log("Custom message : " + response.responseText);
            }, //Is Called when Status Code is 200[OK] or other Http success code
            error: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
            })
    

    Additionally you can handle different HTTP errors from jQuery side like:

    $.ajax({
            type: "POST",
            url: "/General/ContactRequestPartial",
            data: {
                HashId: id
            },
            statusCode: {
                500: function (jqXHR, textStatus, errorThrown)  {
                    console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
                501: function (jqXHR, textStatus, errorThrown)  {
                    console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
                }
            })
    

    statusCode: is useful when you want to call different functions for different status codes that you return from server.

    You can see list of different Http Status codes here:Wikipedia

    Additional resources:

    1. Returning Server-Side Errors from AJAX Calls
    2. Returning a JsonResult within the Error function of JQuery Ajax
    3. Handling Ajax errors with jQuery

提交回复
热议问题