我想控制什么时候回复错误消息,当成功消息,但我总是得到错误消息:
这里是我想做的:
$.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);
}
}