2010-09-30 27 views
0

我正在使用MVC 2.在視圖中使用的基本控制器的屬性

我有一個每個控制器使用的BaseController類。在這個基礎控制器類中有一個名爲IsAdministrator的屬性。我需要在我的視圖的HTML部分中使用此方法。我將如何做到這一點?

編輯:

我在我的BaseController財產的定義是這樣的:

public bool IsAdministratorUser 
{ 
    get { return ... } 
} 
+0

根據達林的回答如下,但在這種情況下,省略括號,即<%if(Html.IsAdministratorUser ){%> – 2010-09-30 10:34:20

回答

14

的一種方法是使用一個HTML幫助:

public static class HtmlExtensions 
{ 
    public static bool IsAdministrator(this HtmlHelper htmlHelper) 
    { 
     var controller = htmlHelper.ViewContext.Controller as BaseController; 
     if (controller == null) 
     { 
      throw new Exception("The controller used to render this view doesn't inherit from BaseContller"); 
     } 
     return controller.IsAdministrator; 
    } 
} 

而在你的看法:

<% if (Html.IsAdministrator()) { %> 

<% } %> 

更新:

@ jfar關於MVC範式的評論是正確的。以下是您在實踐中可以執行的操作。你可以定義你的所有視圖模型派生自基礎視圖模型類:

public class BaseViewModel 
{ 
    public bool IsAdministrator { get; set; } 
} 

,然後寫一個自定義的行爲過濾屬性將動作後執行,並設置屬性:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] 
public class AdministratorInjectorAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
     base.OnActionExecuted(filterContext); 
     var result = filterContext.Result as ViewResultBase; 
     if (result != null) 
     { 
      // the action returned a strongly typed view and passed a model 
      var model = result.ViewData.Model as BaseViewModel; 
      if (model != null) 
      { 
       // the model derived from BaseViewModel 
       var controller = filterContext.Controller as BaseController; 
       if (controller != null) 
       { 
        // The controller that executed this action derived 
        // from BaseController and posses the IsAdministrator property 
        // which is used to set the view model property 
        model.IsAdministrator = controller.IsAdministrator; 
       } 
      } 
     } 
    } 
} 

而且最後一部分是與此屬性裝飾BaseController:

[AdministratorInjector] 
public abstract class BaseController : Controller 
{ 
    public bool IsAdministrator { get; set; } 
} 

最後,如果你的看法是強類型的,以從派生的模型你可以直接使用IsAdministrator屬性:

<% if (Model.IsAdministrator) { %> 

<% } %> 

可能比HTML幫助更多的代碼,但是你要尊重MVC模式將是明確的意識。

+0

+1 darin,像往常一樣好:)。我想補充一點,如果它將被用在視圖中的一些地方,那麼將這種助手調用緩存到變量中也很有用。即<%bool isAdminUser = Html.IsAdministrator();%>,然後只需參考<%if(isAdminUser){%> etc等。 – 2010-09-30 09:26:24

+0

@Darin:你是MVC的一個棺材:) – 2010-09-30 09:48:29

+0

@Darin:How我會讓IsAdministrator顯示在Html助手中嗎?它現在不在嗎? – 2010-09-30 09:51:53

相關問題