views:

23

answers:

2

Say I have a class that wraps the Controller class:

public class MyController : Controller
{
    public string SomeProperty {get;set;}

    public override void OnActionExecuting(...) 
    {
          SomeProperty = "hello";
    }

}

Now in my site.master, I want to have access to the SomeProperty that I just set.

How can I do this?

+2  A: 

If the ViewData.Model type is known you can set it via:

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

        base.OnActionExecuted(filterContext);
    }

Now SomeProperty will be populated in your View's Model.

If you don't know the model type you can always use the ViewData dictionary.

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

        base.OnActionExecuted(filterContext);
    }
jfar
+1  A: 

In each view <%= ViewContext.Controller %> will give you the instance of the controller that rendered this view. If you have a base controller for all actions and the property is on this base controller you could cast and access the property. Writing a helper method to do this might be even better:

<%= Html.SomeProperty() %>

with the following helper defined:

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));
}
Darin Dimitrov
@Darin Dimitrov Controller Properties as ViewData? How could you recommend this? Crazy!
jfar
I agree with jfar, this is crazy!
Ryan
I never said that I recommend this. I just answered the question.
Darin Dimitrov