views:

231

answers:

1

Hi,

I've created an OnActionExecuted filter to populate some viewmodel attributes with data from db (I'm not using ViewData["somekey"], preferring many ViewModels descending from a common ancestor).

public class BaseController : Controller
{
    protected DataClassesDataContext context = new DataClassesDataContext();

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        ViewModel model = (ViewModel) ViewData.Model;
        model.IsUserAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
        if (model.IsUserAuthenticated)
        {
            model.UserName = filterContext.HttpContext.User.Identity.Name;
        }
        model.CommonAttribute = from c in context.Something select new SomethingElse() {...};
    }
}

The problem is that when an action results in a redirect or a 404 error, OnActionExecuted tries to access ViewModel, which has not been initialized. Also, it's completely useless to fill those values, as they will not be used, since another action is going to be called.

How can I avoid filling viewodel on redirect?

+2  A: 

A trivial solution would be to not fill in the model when it doesn't exist:

ViewModel model = ViewData.Model as ViewModel;
if (model != null)
{    
    model.IsUserAuthenticated = filterContext.HttpContext.User.Identity.IsAuthenticated;
    if (model.IsUserAuthenticated)
    {
        model.UserName = filterContext.HttpContext.User.Identity.Name;
    }
    model.CommonAttribute = from c in context.Something select new SomethingElse() {...};
}
Craig Stuntz
why not? thanks
giorgian