When implementing error-handling using the built-in validation-helpers on a strongly-typed view, you usually create a try/catch block within the controller and return a view with it's corresponding model as a parameter to the View()
method:
The controller
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);
}
}
}
The view
<%@ 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>
<% } %>
I've implemented a simple error-handler in the form of an ActionFilterAttribute, which will be able to either redirect to a generic error view, or redirect to the view which threw an exception, and let the validation-helpers spring to life.
Here's how my ActionFilterAttribute looks:
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;
}
}
}
Redirecting to the view which threw the exception is fairly simple. But here's the kicker: In order for the validation helpers to work, you need to provide the view with it's model.
How would you return the view which threw an exception and provide the view with it's corresponding model? (In this case Models.Entities.Message
).
I got it to work!
For some odd reason, all I needed to do was to pass on the
ViewData
to a newResultView
.Here's the complete code:
Usage
Here's how you would use the attribute on a controller-action, to redirect to the same view (with it's associated model) to enable standard validation-helpers to kick in, when an exception occurs:
And here's how you would use the attribute, to redirect to a generic view, when an exception occurs:
This is a complete separation of logic. Nothing in the controller but the very basics.
The details of the model are already present in modelstate. Any errors should also already be present in modelstate. Your exception handler only needs to handle the case where you want to redirect to a generic error page. Better / more obvious is to throw the attribute away and if you want to redirect in the catch, return a redirect result.
Since you inherit from ActionFilterAttribute From OnActionExecuting, you can grab your model.
But there is already HandleError defined in MVC system, why don't you use this one instead of baking your own.
I suggest you read this blog on this issue.
If your action throws exception, there's no way to pass the model to the view since the model is not probably created yet - or not fully created. That's probably why the result is null. You can't rely on the data after exception was thrown.
But you can pass pass "default" model to your action filter like this:
This way your filter will pass this "error model" that you explicitely set to be displayed when an error happened.