Jquery Ajax,从 mvc.net 控制器返回成功/错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26605065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:17:25  来源:igfitidea点击:

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

jqueryasp.net-mvc

提问by Eyal

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:

这是我想要做的:

 $.ajax({
                type: "POST",
                data: formData,
                url: "/Forms/GetJobData",
                dataType: 'json',
                contentType: false,
                processData: false,

                success: function (response) {                    
                   alert("success!") 
                },
                error: function (response) {
                   alert("error") // I'm always get this.
                }

            });

Controller:

控制器:

         [HttpPost]
            public ActionResult GetJobData(Jobs jobData)
            {

              var mimeType = jobData.File.ContentType;
              var isFileSupported = AllowedMimeTypes(mimeType);

             if (!isFileSupported){        
                     //  Error
                    Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return Content("The attached file is not supported", MediaTypeNames.Text.Plain);    
             }
            else
              {
                    //  Success
                    Response.StatusCode = (int)HttpStatusCode.OK;
                    return Content("Message sent!", MediaTypeNames.Text.Plain);     

               }   

            }

回答by Eyal

 $.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!"); 
                }
            });

回答by SBirthare

Use Jsonclass instead of Contentas shown following:

使用Json类而不是Content如下所示:

    //  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',

回答by Tekin

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

当您从服务器返回值到 jQuery 的 Ajax 调用时,您还可以使用以下代码来指示服务器错误:

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).

Http Success 代码以外的代码(例如 200[OK])将触发error:客户端(ajax)前面的函数。

you can have ajax call like:

你可以有 ajax 调用,如:

$.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:

此外,您可以从 jQuery 端处理不同的 HTTP 错误,例如:

$.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.

statusCode:当您想为从服务器返回的不同状态代码调用不同的函数时非常有用。

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

您可以在此处查看不同 Http 状态代码的列表:维基百科

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
  1. 从 AJAX 调用返回服务器端错误
  2. 在 JQuery Ajax 的 Error 函数中返回一个 JsonResult
  3. 使用 jQuery 处理 Ajax 错误