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?