【发布时间】:2009-11-03 19:18:37
【问题描述】:
在强类型视图上使用内置验证助手实现错误处理时,您通常会在控制器中创建一个 try/catch 块,并将其对应模型的视图作为参数返回给 View()方法:
控制器
public class MessageController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Models.Entities.Message message)
{
try
{
// Insert model into database
var dc = new DataContext();
dc.Messages.InsertOnSubmit(message);
dc.SubmitChanges();
return RedirectToAction("List");
}
catch
{
/* If insert fails, return a view with it's corresponding model to
enable validation helpers */
return View(message);
}
}
}
视图
<%@ Page
Language="C#"
Inherits="System.Web.Mvc.ViewPage<Models.Entities.Message>" %>
<%= Html.ValidationSummary("Fill out fields marked with *") %>
<% using (Html.BeginForm()) { %>
<div><%= Html.TextBox("MessageText") %></div>
<div><%= Html.ValidationMessage("MessageText", "*") %></div>
<% } %>
我以 ActionFilterAttribute 的形式实现了一个简单的错误处理程序,它将能够重定向到通用错误视图,或重定向到引发异常的视图,并让验证助手栩栩如生。
这是我的 ActionFilterAttribute 的外观:
public class ErrorLoggingAttribute : ActionFilterAttribute, IExceptionFilter
{
private Boolean _onErrorRedirectToGenericErrorView;
/// <param name="onErrorRedirectToGenericErrorView">
/// True: redirect to a generic error view.
/// False: redirect back the view which threw an exception
/// </param>
public ErrorLoggingAttribute(Boolean onErrorRedirectToGenericErrorView)
{
_onErrorRedirectToGenericErrorView = onErrorRedirectToGenericErrorView;
}
public void OnException(ExceptionContext ec)
{
if (_onErrorRedirectToGenericErrorView)
{
/* Redirect back to the view where the exception was thrown and
include it's model so the validation helpers will work */
}
else
{
// Redirect to a generic error view
ec.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"controller", "Error"},
{"action", "Index"}
});
ec.ExceptionHandled = true;
}
}
}
重定向到引发异常的视图相当简单。但关键是:为了让验证助手工作,您需要为视图提供它的模型。
您将如何返回引发异常的视图并为视图提供相应的模型? (在本例中为 Models.Entities.Message)。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-routing