0
是否可以在呈现_layout.cs文件之前设置ViewBag
属性?我需要ViewBag
包含一个我可以用来渲染_layout的列表。我怎样才能做到这一点?在渲染_layout.cs文件之前设置ViewBag
我听说过StartUp.cs,但我认为这是OWIN,不能在这里使用,是正确的吗?
是否可以在呈现_layout.cs文件之前设置ViewBag
属性?我需要ViewBag
包含一个我可以用来渲染_layout的列表。我怎样才能做到这一点?在渲染_layout.cs文件之前设置ViewBag
我听说过StartUp.cs,但我认为这是OWIN,不能在这里使用,是正确的吗?
您可以创建自定义ActionFilter
来设置ViewBag
属性。
public class CustomViewBagActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// either inject a property or use the filterContext
//to get what data you need to use to set the ViewBag
dynamic ViewBag = filterContext.Controller.ViewBag;
ViewBag.Test = "test";
}
}
然后你可以全局应用这样的FilterConfig.cs
:
filters.Add(new CustomViewBagActionFilter());
或者你可以用它装饰你的控制器或者动作:
[CustomViewBagActionFilter]
public class HomeController : Controller
然后你就可以访问ViewBag属性在_Layout.cs文件中。只要确保检查为null并根据ViewBag数据进行相应处理即可。
最后我试了一下,在你的布局中设置了ViewBag属性。你有什么尝试? – mxmissile 2015-02-11 14:48:46