0

When I do Ajax.BeginForm posts to my actions returning a partial view I send error info in a ViewData item.

Currently in order to handle all errors I must wrap all of the method in a try catch statement.

[HttpPost, ValidateAntiForgeryToken]
public virtual ActionResult Save(int id, FormCollection form)
{
    MyModel model;
    try
    {
        ...do stuff...

    }
    catch(Exception ex)
    {
        ...log...
        ViewData["ResultInfo"] = new ResultInfo(false, Resource.SAVE_NOT_SAVED, someErrorMessage);
    }

    return PartialView("Folder/SomeView", model);
}

I would like to do this with a custom HandleError attribute, but I realize that there must be many gotchas waiting to bite. Has anyone tried and want to share their experiences?

EDIT:
I've ended up doing error handling in a controller base class.

This ErrorHandlingController has 2 methods; RegisterErrorHandler and RegisterModel. If the error handler is found registered when an error is found in the base class OnException I just add the ResultInfo and marks the error as handled and uses the view and error caption I've set in RegisterErrorHandler.

This way it's very easy to get the model to the error handler and it's natural to use Resources directly since the error handler is registered as the first row inside the method as opposed to an attribute outside it.

Carl R
  • 8,104
  • 5
  • 48
  • 80

1 Answers1

1

I think the answer to this question will help you along: How to handle model state errors in ajax-invoked controller action that returns a PartialView.

Community
  • 1
  • 1
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
  • That's an interesting post +1, but there's an issue with that solution applied to Ajax.BeginForms. For the form not to go blank, one would need to at least return an empty model rendered with the associated view. – Carl R May 05 '11 at 08:00
  • @Carl R - Well, on the plus side, it'd kind of force you to adopt a good practice such as creating a view model for that view, which, as an added bonus, would allow you to get rid of that ugly `FormsCollection` parameter ;) – Sergi Papaseit May 05 '11 at 08:14
  • Well "MyModel" is a viewmodel and that ugly FormsCollection parameter is the easiest part to implement as it's easily reachable from a HandleError subclass. Creating a viewmodel of the right kind and returning the correct view is the hard part. :) – Carl R May 05 '11 at 08:35