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", data: formData, url: "/Forms/GetJobData", dataType: 'json', contentType: false, processData: false, 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); } } 

– -补充: – –

基本上你可以这样发送多个参数:

控制器:

  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) { console.log(response.Name); console.log(response.Phone); console.log(response.Email); }, error: function (response) { alert("error!"); } }); 

使用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',