我想知道向浏览器报告将向用户显示的应用程序或模型状态错误的最佳做法是什么。你可以抛出一个异常并在jquery帖子的错误处理程序中处理它吗?例如,请考虑以下方法:
[HandlerErrorWithAjaxFilter, HttpPost]
public ActionResult RetrievePassword(string email)
{
User user = _userRepository.GetByEmail(email);
if (user == null)
throw new ClientException("The email you entered does not exist in our system. Please enter the email address you used to sign up.");
string randomString = SecurityHelper.GenerateRandomString();
user.Password = SecurityHelper.GetMD5Bytes(randomString);
_userRepository.Save();
EmailHelper.SendPasswordByEmail(randomString);
if (Request.IsAjaxRequest())
return Json(new JsonAuth { Success = true, Message = "Your password was reset successfully. We've emailed you your new password.", ReturnUrl = "/Home/" });
else
return View();
}
当用户为null时,在这种情况下抛出异常是否正确?或者我应该这样做并在jquery帖子的成功处理程序中处理它:
return Json(new JsonAuth { Success = false, Message = "The email you entered does not exist in our system. Please enter the email address you used to sign up.", ReturnUrl = "/Home/" });
答案 0 :(得分:5)
不要通过抛出异常来处理验证。如果您要发送JSON响应,请在JSON响应中包含客户端所需的全部内容:
return Json(new JsonAuth {
Success = false,
Message = "The email you entered does not exist in our system. Please enter the email address you used to sign up.",
ReturnUrl = "/Home/"
});
如果您要返回视图,请添加模型状态错误,表单上的HTML帮助程序将完成剩下的工作:
ModelState.AddModelError("email", "The email you entered does not exist in our system. Please enter the email address you used to sign up.");
return View();