2009-08-28 15 views
0

OnActionExecutedフィルタを作成して、一部のviewmodel属性にdbのデータを設定しました(ViewData ["somekey"]を使用していません)。共通の祖先)。ASP.NET MVC:リダイレクトでactionfiltersを実行せず、HttpExceptionをスローしない

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が初期化されていないビューモデルにアクセスしようとしたとき。また、別のアクションが呼び出されるため、使用されないため、これらの値を埋めることは全く無意味です。

リダイレクト時にViewDelを埋めるのを避けるにはどうすればよいですか?

答えて

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() {...}; 
} 
+0

理由は?ありがとう – giorgian

関連する問題