Ive MVC5应用程序和我使用以下代码来调用该操作 在控制器中,这工作正常。我在这里遗漏的一件事是 我应该如何从控制器中删除消息(就像无法保存一样)。 我如何将此错误消息发送给ui?
我问它因为我使用AJAX调用动作而不是常规方式...
// Send data to the controller from the index view
$.ajax({
type: "POST",
url: '@Url.Action("Create", "Users")',
data: Data,
success: successCreation,
error: errorCreation,
dataType: "json"
});
这是控制器方法
[HttpPost]
public int Create(Users users)
{
try
{
if (ModelState.IsValid)
{
db.Users.Add(users);
db.SaveChanges();
}
}
catch (Exception)
{
throw new Exception("Test Exception");
}
return users.Id;
}
答案 0 :(得分:1)
控制器代码:
// POST: /HandlejQueryErrors/Contact/Create
[HttpPost]
public ActionResult Create(Users users)
{
var response = new AjaxResponseViewModel();
try
{
if (ModelState.IsValid)
{
db.Users.Add(users);
db.SaveChanges();
}
}
catch (Exception exception)
{
response.Success = false;
response.Messages exception.Message;
}
return Json(response);
}
将此添加到您的Ajax请求中
error: function ( xhr, errorType, exception ) { //Triggered if an error communicating with server
var errorMessage = exception || xhr.statusText; //If exception null, then default to xhr.statusText
alert( "There was an error creating your contact: " + errorMessage );
}
如需更多帮助,请查看以下链接:Ajax Error Handler。
如果能解决您的问题,请告诉我。
答案 1 :(得分:0)
您的代码很好,唯一要添加的是您的自定义HandleErrorAttribute过滤器,因此您的控制器代码与错误处理分离(在关注点分离之后:)。
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
HandleErrorForAjax(filterContext); // return json-encoded error description
}
else
{
base.OnException(filterContext); //handle web requests as usual
}
}
所以最终,你的js代码会收到500个代码并触发“错误”处理程序。
(我不建议{success = false}方法,因为它返回200个http代码并打破RESTful范例)