我想控制何时回复错误消息和成功消息,但我总是收到错误消息:
以下是我要做的事情:
$.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);
}
}
答案 0 :(得分:103)
$.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!");
}
});
答案 1 :(得分:28)
使用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',
答案 2 :(得分:0)
当您从服务器返回值到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
其他资源:
答案 3 :(得分:0)
当您从 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" });
}
}