2010-06-03 12 views

回答

1

在每个视图<%= ViewContext.Controller %>会给你呈现这个视图控制器的实例。如果您拥有所有操作的基础控制器,并且该基础控制器上的属性可以投射并访问该属性。写一个辅助方法来做到这一点可能会更好:

<%= Html.SomeProperty() %> 

,并定义了下面的帮助:

public static MvcHtmlString SomeProperty(this HtmlHelper htmlHelper) 
{ 
    var controller = htmlHelper.ViewContext.Controller as BaseController; 
    if (controller == null) 
    { 
     // The controller that rendered this view was not of type BaseController 
     return MvcHtmlString.Empty; 
    } 
    return MvcHtmlString.Create(htmlHelper.Encode(controller.SomeProperty)); 
} 
+0

控制器属性作为ViewData的?你怎么能推荐这个?疯! – jfar 2010-06-03 21:40:47

+0

我同意jfar,这是疯了! – Ryan 2010-06-03 23:58:37

+0

我从来没有说过我推荐这个。我刚刚回答了这个问题。 – 2010-06-04 06:10:32

2

如果ViewData.Model类型是已知的,你可以通过设置:

protected override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext) 
{ 
    var myModel = ((ViewResult) filterContext.Result).ViewData.Model as ProfessionalMembership; 
    myModel.SomeProperty = "hello"; 

    base.OnActionExecuted(filterContext); 
} 

现在SomeProperty将在您查看的模式来填充。

如果您不知道模型类型,则始终可以使用ViewData字典。

protected override void OnActionExecuted(System.Web.Mvc.ActionExecutedContext filterContext) 
{ 
    ((ViewResult) filterContext.Result).ViewData["Propery"] = "asdf"; 

    base.OnActionExecuted(filterContext); 
} 
相关问题