2012-03-23 10 views
5

MVCアプリケーションでは、その役割に基づいて異なるアクションビューを提示する必要があります。これを行う最善の方法は何ですか?MVC - ユーザー役割に基づくビューの切り替え

現在、私は私が好きではない次のコードを持っている:

if (HttpContext.User.IsInRole("Admin")) 
    return View("Details.Admin", model); 
else if (HttpContext.User.IsInRole("Power")) 
    return View("Details.Power", model); 

//default 
return View("Details", model); 

が、これはアクションフィルタに適してでしょうか?

答えて

6

これはアクションフィルタに適していますか?

絶対に:

public class MyActionFilterAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     var result = filterContext.Result as ViewResultBase; 
     if (result != null) 
     { 
      var user = filterContext.HttpContext.User; 
      if (user.IsInRole("Admin")) 
      { 
       result.ViewName = string.Format("{0}.Admin", filterContext.ActionDescriptor.ActionName); 
      } 
      else if (user.IsInRole("Power")) 
      { 
       result.ViewName = string.Format("{0}.Power", filterContext.ActionDescriptor.ActionName); 
      } 
     } 
    } 
} 

それともあなたもカスタムビューのエンジンを構築することができます。

+0

ビューエンジンの作成を保証するのに十分な例はありませんが、私はアクションフィルタのアプローチがおそらく良いと考えていました。ありがとうダーリン – Dismissile

関連する問題