我已经创建了一个OnActionExecuted过滤器,用db中的数据填充一些viewmodel属性(我不使用ViewData [“somekey”],更喜欢从共同祖先下降的许多ViewModel)。
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() {...};
}
}
问题是,当某个操作导致重定向或404错误时,OnActionExecuted会尝试访问尚未初始化的ViewModel。此外,填充这些值完全没用,因为它们不会被使用,因为将要调用另一个动作。
如何避免在重定向上填充viewodel?
答案 0 :(得分:2)
一个简单的解决方案是在模型不存在时不填写模型:
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() {...};
}