I set a property in my custom controller wrapper in OnActionExecuting, how to pass to Site.Master?
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?
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);
}
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));
}
精彩评论