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

后端 未结 3 534
庸人自扰
庸人自扰 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条回答
  • 2020-12-08 00:27
     $.ajax({
        type: "POST",
        data: formData,
        url: "/Forms/GetJobData",
        dataType: 'json',
        contentType: false,
        processData: false,               
        success: function (response) {
            if (response.success) {
                alert(response.responseText);
            } else {
                // DoSomethingElse()
                alert(response.responseText);
            }                          
        },
        error: function (response) {
            alert("error!");  // 
        }
    
    });
    

    Controller:

    [HttpPost]
    public ActionResult GetJobData(Jobs jobData)
    {
        var mimeType = jobData.File.ContentType;
        var isFileSupported = IsFileSupported(mimeType);
    
        if (!isFileSupported){        
             //  Send "false"
            return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            //  Send "Success"
            return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
        }   
    }
    

    ---Supplement:---

    basically you can send multiple parameters this way:

    Controller:

     return Json(new { 
                    success = true,
                    Name = model.Name,
                    Phone = model.Phone,
                    Email = model.Email                                
                }, 
                JsonRequestBehavior.AllowGet);
    

    Html:

    <script> 
         $.ajax({
                    type: "POST",
                    url: '@Url.Action("GetData")',
                    contentType: 'application/json; charset=utf-8',            
                    success: function (response) {
    
                       if(response.success){ 
                          console.log(response.Name);
                          console.log(response.Phone);
                          console.log(response.Email);
                        }
    
    
                    },
                    error: function (response) {
                        alert("error!"); 
                    }
                });
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-08 00:44

    Use Json class instead of Content as shown following:

        //  When I want to return an error:
        if (!isFileSupported)
        {
            Response.StatusCode = (int) HttpStatusCode.BadRequest;
            return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
        }
        else
        {
            //  When I want to return sucess:
            Response.StatusCode = (int)HttpStatusCode.OK; 
            return Json("Message sent!", MediaTypeNames.Text.Plain);
        }
    

    Also set contentType:

    contentType: 'application/json; charset=utf-8',
    
    0 讨论(0)
提交回复
热议问题