【问题标题】:Jquery Ajax, return success/error from mvc.net controllerJquery Ajax,从 mvc.net 控制器返回成功/错误
【发布时间】:2014-12-23 15:57:19
【问题描述】:

我想控制何时回复错误消息以及何时回复成功消息,但我总是收到错误消息:

这是我想要做的:

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

            });

控制器:

         [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);     

               }   

            }

【问题讨论】:

  • 添加if 条件...我不确定您在这里期待什么答案。
  • 您的点击错误,因为第一个 return 语句之后的代码没有运行。您可能希望将代码移到成功注释之后,前一个 return 语句之前。
  • 我解决了这个问题。现在我的问题很清楚了。
  • 这个问题已经有好几年了,但是您可能收到错误的原因是您的 Ajax 请求中的 datatype 参数。您告诉 Ajax 期待 JSON,但您返回的是纯文本:Ajax: "datatype": The type of data that you're expecting back from the server

标签: jquery asp.net-mvc


【解决方案1】:
 $.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!");  // 
    }

});

控制器:

[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);
    }   
}

---补充:---

基本上你可以通过这种方式发送多个参数:

控制器:

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

【讨论】:

  • contentType: 'application/json; charset=utf-8'false?为什么?
  • 我添加了 contentType: 'application/json; charset=utf-8', processData: false 对我有用。
  • @ClintEastwood contentType 是你要发送的数据类型,所以需要设置为json,一个很常见的就是'application/json; charset=utf-8'.
  • 总会命中ajax调用成功事件。我想要的是在某些东西不可用或错误时触发 ajax 调用的失败/错误处理程序。
  • 这是一个很好的解决方案,但并没有真正解释为什么它很好。根据来自 JQuery 文档的 Ajax 规范:"error": A function to be called if the request fails. 在 OP 的示例中,请求到达服务器并被处理,它产生了一个可预测的状态,此时无法解决;而不是意外错误(即错误的 HTTP 动词、404 等)。因此,通过在success 函数中进行管理,您可以区分正常行为和意外的服务器错误。 IE。服务器请求成功,返回“bad file state”消息。
【解决方案2】:

使用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);
    }

同时设置 contentType:

contentType: 'application/json; charset=utf-8',

【讨论】:

  • contentType: 'application/json; charset=utf-8'false?为什么?
  • 我喜欢这个答案,因为它提供了Response.StatusCode 集合的示例。
  • @ClintEastwood contentType 是你要发送的数据类型,所以需要设置为json,一个很常见的就是'application/json; charset=utf-8'.
  • 不错,它应该是正确的答案
【解决方案3】:

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

return StatusCode(500, "My error");

或者

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

或者

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

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

你可以像这样进行 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
        })

此外,您还可以从 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: 在您想为从服务器返回的不同状态代码调用不同函数时很有用。

您可以在此处查看不同 Http 状态代码的列表:Wikipedia

其他资源:

  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

【讨论】:

    【解决方案4】:

    当您从 Controller 返回错误请求时,将触发全局异常。 可能客户端显示错误页面,所以jquery得到200响应。

    解决方案 1:

    控制器

    [HttpPost]
    public ActionResult FooAction(string id, string[] orderFields)
    {
        bool hasError = true; //TODO: Validation
    
        if (hasError)
        {
           Response.Clear();
           Response.TrySkipIisCustomErrors = true; //the magic
           Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    
           return Json(new { success = false, message = "test error", status = 500 });
        }
        else
        {
           return Json(new { success = true, message = "ok", status = 200 });
        }
    }
    

    查看:

    <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: url,
            data: { orderFields: order },
            success: function (response) {
                if (response.success) {
                    alert("Ok");
                }
            },
            error: function (xhr, status, error) {
                if (xhr.responseText != "") {
                    var err = JSON.parse(xhr.responseText);
                    if (err.status == 440) {
                        alert("Session expired");
                    }
                    else {
                        alert(err.message);
                    }
                }
                else {
                    alert("Crash");
                }
            }
        });
    </script>
    



    解决方案 2: (更优雅)
    创建自定义属性

    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Net;
    using System.Web.Mvc;
    
    public class ExceptionJsonMvcAttribute : FilterAttribute, IExceptionFilter
    {
        public virtual void OnException(ExceptionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("filterContext");
            }
    
            if (context.Exception == null)
                return;
    
            int status;
            string message;
            var ex = context.Exception;
            var exceptionType = ex.GetType();
            if (exceptionType == typeof(UnauthorizedAccessException))
            {
                var exAccess = (UnauthorizedAccessException)ex;
                message = exAccess.Message;
                status = (int)HttpStatusCode.Unauthorized;
            }
            else if (exceptionType == typeof(SqlException))
            {
                var exSql = (SqlException)ex;
                message = GetDbMessage(exSql);
                status = (int)HttpStatusCode.BadRequest;
            }
            else if (exceptionType == typeof(KeyNotFoundException))
            {
                var exNotFound = (KeyNotFoundException)ex;
                message = exNotFound.Message;
                status = (int)HttpStatusCode.NotFound;
            }
            else
            {
                message = ex.Message;
                status = (int)HttpStatusCode.InternalServerError;
            }
    
    
            string json = ""; // TODO: Json(new { success = false, message = message, status = status });
            context.ExceptionHandled = true;
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.TrySkipIisCustomErrors = true;
            context.HttpContext.Response.StatusCode = status;
            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Response.Write(json);
        }
    
        private string GetDbMessage(SqlException exSql)
        {
            //TODO: Remove generic from database
    
            return "DataBase Error see log";
        }
    }
    

    注意 ApiController 使用 System.Net.Http 而不是 System.Web.Mvc


    控制器:

    [ExceptionJsonMvc]
    [HttpPost]
    public ActionResult FooAction(string id, string[] orderFields)
    {
        bool hasError = true; //TODO: Validation
    
        if (hasError)
        {
           throw new Exception("test error");
        }
        else
        {
           return Json(new { success = true, message = "ok" });
        }
    }
    

    【讨论】:

      【解决方案5】:

      .Net Core 版本,使用状态码表示服务器错误

      C#代码

      public string methodName(int param1)
         {
         try{
              Response.StatusCode = 200;
              return "";
          }
         catch {
              Response.StatusCode = 400;
              return "";
              }
         }
      

      ajax 调用:

       $.ajax({
       type: 'get',
       url: 'your url',
       data: {"param1":value1},
       success: function (data) {
          alert("success");
          },
        error: function () {
          alert("failed");
          }
       });
      

      【讨论】:

        猜你喜欢
        • 2020-11-12
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2020-08-13
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        相关资源
        最近更新 更多