MVC3如何动态添加验证错误

时间:2012-07-05 16:15:23

标签: asp.net-mvc-3 razor data-annotations

我正在尝试在视图上显示错误消息。能否建议我采取正确的方法来做到这一点。我正在考虑动态添加数据注释,但找不到任何解决方案。

谢谢

[HttpPost]
public ActionResult AddBook(BooksModel booksModel)
{           
    try
    {
        booksModel.Account = _bookRepository.BookDetails(booksModel.Title,booksModel.RefCode, booksModel.DontHaveRefCode);
    }
    catch (FaultException faultException)
    {
        switch (faultException.Code.Name)
        {
            case "exc1":
            // Show Error Message Here
            return View("AddBook", booksModel);
            default:
            break;
        }
    }
    return View("ConfirmBook", booksModel);
}

1 个答案:

答案 0 :(得分:5)

我认为你在寻找:

[HttpPost] 
public ActionResult AddBook(BooksModel booksModel) 
{            
    try 
    { 
        booksModel.Account = _bookRepository.BookDetails(booksModel.Title,booksModel.RefCode, booksModel.DontHaveRefCode); 
    } 
    catch (FaultException faultException) 
    { 
        switch (faultException.Code.Name) 
        { 
            case "exc1": 

            ModelState.AddModelError("", faultException);
            return View("AddBook", booksModel); 
            default: 
            break; 
        } 
    } 
   return View("ConfirmBook", booksModel); 
}