.net - 向客户报告模型状态和应用程序错误的推荐方法是什么?

标签 .net jquery asp.net asp.net-mvc asp.net-mvc-2

我想知道向浏览器报告将显示给用户的应用程序或模型状态错误的最佳实践是什么。你能抛出一个异常并在jquery post的错误处理程序中处理它吗?例如,考虑以下方法:

[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();           
        }

在这种情况下,当用户为空时抛出异常是否正确?或者我应该这样做并在 jquery post 的成功处理程序中处理它:

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/" });

最佳答案

不要通过抛出异常来处理验证。如果您要发送 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/" 
});

如果您要返回 View ,请添加模型状态错误,表单上的 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();

关于.net - 向客户报告模型状态和应用程序错误的推荐方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5171684/

相关文章:

javascript - jQuery:使用切片选择元素

javascript - 仅当图像具有 .landscape 类时,如何将类添加到容器 div?

asp.net - ASP.NET MVC 如何在不显式传递模型的情况下将模型传递给 View

c# - AutoMapper 无法使用 ASP.NET Core 将 List<Model>(1 项)转换为 List<DTO>(0 项)

asp.net - 开源 ASP.NET CMS

C# 和并发读取线程安全对象?

c# - .net TransactionScope 异常

javascript - 将值从 javascript 插入数据库

.net - .Net 中的异步文件 IO

c# - .NET - RichTextBox 中的长行在 3,510 个字符后换行