我需要将操作的错误状态返回到视图。我当时在使用JsonResult
,但是现在我需要使用ActionResult
。对于JsonResult
,它的工作方式如下:
操作示例
[HttpPost]
public JsonResult Page(Guid? id)
{
try
{
if (id == Guid.Empty)
{
return new JsonHttpStatusResult("The ID is Empty", HttpStatusCode.BadRequest);
}
var model = ArquivoManager.List(id, ref db);
if (model == null)
{
return new JsonHttpStatusResult("Not Found", HttpStatusCode.NotFound);
}
return Json(model, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return new JsonHttpStatusResult(ex.Message, HttpStatusCode.InternalServerError);
}
}
JsonHttpStatusResult
public class JsonHttpStatusResult : JsonResult
{
private readonly HttpStatusCode _httpStatus;
public JsonHttpStatusResult(object data, HttpStatusCode httpStatus)
{
Data = data;
_httpStatus = httpStatus;
}
public override void ExecuteResult(ControllerContext context)
{
context.RequestContext.HttpContext.Response.StatusCode = (int)_httpStatus;
base.ExecuteResult(context);
}
}
查看AJAX
$.ajax({
type: "POST",
url: '/School/Page',
dataType: "json",
success: function (resposta) {
//something
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError.toUpperCase() + ": " + xhr.responseJSON);
}
});
我需要使用JsonResult
来实现我的行动,而不是ActionResult
,所以我想要一个类似的解决方案。