2012-01-26 7 views
0

多くのロールがあり、各ロールには多くの機能があるため、私の場合はRequireRoles属性で十分ではないと思います。私は、動的にコントローラのアクションを定義するための何らかの方法が必要です。ビュー内のセクションやコントロールを表示します(ビュー内にif/elseロジックを追加しないでください)。MVC 3 - ロール/ファンクションによるビューのセクションやコントロールの制限

私の考えは、コントローラがビューにif/elseロジックで表示するのではなく、表示する方法を伝えるべきだと考えました。

これはどのように設計するのですか?

答えて

0

まず、属性を使用してどのアクションをどのロールに表示するかを制御できるフィルタを作成する必要があります。 http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/understanding-action-filters-csを参照してください。

public class RequiresRoleAttribute : ActionFilterAttribute { 
    private List<string> requiredRoles = null; 

    /// <summary> 
    /// Initializes a new instance of the <see cref="RequiresRoleAttribute"/> class. 
    /// </summary> 
    /// <param name="roleNames">The role names.</param> 
    public RequiresRoleAttribute(params string[] roleNames) { 
     this.requiredRoles = new List<string>(roleNames); 
    } 

    /// <summary> 
    /// Called by the MVC framework before the action method executes. 
    /// </summary> 
    /// <param name="filterContext">The filter context.</param> 
    public override void OnActionExecuting(ActionExecutingContext filterContext) { 
     bool hasRole = false; 

     // check to see if the user has the proper role here 

     // if the do not have the role, they are not allowed to execute the action 
     if (!hasRole) 
      throw new UserAccessException("You do not have access to this action (" + filterContext.ActionDescriptor.ActionName + ", " + filterContext.ActionDescriptor.ControllerDescriptor.ControllerName + ")"); 

     base.OnActionExecuting(filterContext); 
    } 
} 

第2に、ビュー内にロジックがないという問題を解決するには、役割を必要とするセクションごとに子アクションを使用できます。もう一度、フィルタを子アクションに適用できます。子供の行動の詳細については、http://msdn.microsoft.com/en-us/library/ie/ee839451.aspxを参照してください。

変更する必要があるのは、例外をスローするセクションです。実行されているアクションが子アクションであるかどうかを確認する必要があります。その場合は、空のコンテンツの結果を返すことになります。

関連する問題