【发布时间】:2016-09-29 17:17:15
【问题描述】:
我正在使用 jQuery $.post 将一些数据发布到我的控制器内的 ActionResult 方法。当控制器中抛出错误时,它应该在响应的 responseText 中返回错误消息,但它不起作用。
post 请求正在访问控制器。
似乎触发了回调函数fail。只是没有收到返回的错误消息。不知道我做错了什么?
这是 jQuery 发布数据:
var postData = ["1","2","3"];
$.post('/MyController/GetSomething', $.param(postData, true))
.done(function (data) {
alert('Done!');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText); //xhr.responseText is empty
});
});
控制器
public class MyController : BaseController
{
public ActionResult GetSomething(List ids)
{
try
{
GetSomeData(ids);
}
catch (Exception ex)
{
return ThrowJsonError(new Exception(String.Format("The following error occurred: {0}", ex.ToString())));
}
return RedirectToAction("Index");
}
}
public class BaseController : Controller
{
public JsonResult ThrowJsonError(Exception ex)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
Response.StatusDescription = ex.Message;
return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
更新 有趣的是,如果我将一些逻辑从 BaseController 移到 MyController 中,我就能得到想要的结果。
为什么会这样?
public class MyController : BaseController
{
public ActionResult GetSomething(List<string> ids)
{
try
{
GetSomeData(ids);
}
catch (Exception ex)
{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
Response.StatusDescription = ex.Message;
return Json(new { Message = ex.Message }, JsonRequestBehavior.AllowGet);
}
return RedirectToAction("Index");
}
}
【问题讨论】:
-
是到达控制器还是之前报错?
-
是的,它确实到达了控制器。如果随后在 Controller 中引发异常,则
Message不会以xhr.ResponseText = ""的形式返回 -
如果你把 alert(data.Message);在警报之前(“完成!”);发生了什么?
-
我在这里有一些问题,
GetSomeData(ids);中的内容在此之后您重定向到索引操作,Index中的内容以及您没有将任何数据从GetSomething传递到index -
@DanielVorph 当Controller中抛出异常时,我肯定是在打
.fail(function (xhr, textStatus, errorThrown) { alert(xhr.responseText); //xhr.responseText is empty });函数。
标签: c# jquery asp.net-mvc