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

前端之家收集整理的这篇文章主要介绍了Jquery Ajax,从mvc.net控制器返回成功/错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想控制什么时候回复错误消息,当成功消息,但我总是得到错误消息:

这里是我想做的:

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

               }   

            }

解决方法

$.ajax({
    type: "POST",success: function (response) {
        if (response != null && 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 = AllowedMimeTypes(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);
    }   
}

猜你在找的jQuery相关文章