简体   繁体   English

如何为_Layout.cshtml设置ViewBag属性

[英]How to Set ViewBag Properties for _Layout.cshtml

I am trying to pass a ViewBag property to customize html in _Layout.cshtml. 我试图传递一个ViewBag属性来自定义_Layout.cshtml中的html。

@Styles.Render(ViewBag.IsEnglish ? "~/Content/css-en" : "~/Content/css-ur")

To do this, I have code in my base controller 为此,我在基本控制器中有代码

public class BaseController : Controller
{
    protected virtual void OnAuthorization(AuthorizationContext filterContext)
    {
        ViewBag.IsEnglish = Request.RequestContext.RouteData.Values.ContainsKey("Culture") ?
            (Request.RequestContext.RouteData.Values["culture"].ToString().ToLower() == "en")
            : true;
    }
}

But my _Layout.cshtml gives error where ViewBag is called, before the controller's code setting that property is ever reached. 但是我的_Layout.cshtml在调用ViewBag之前给出了错误,在控制器的代码设置到达该属性之前。 I thought _Layout is executed by the ViewEngine, and ViewEngine runs after Controllers have run. 我认为_Layout是由ViewEngine执行的,而ViewEngine是在控制器运行后运行的。 Where should I place my ViewBag initialization code so that it becomes available to _Layout.cshtml? 我应该在哪里放置我的ViewBag初始化代码,以便_Layout.cshtml可以使用它?

In your base controller, try this: 在您的基本控制器中,试试这个:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    ViewBag.IsEnglish = requestContext.RouteData.Values.ContainsKey("Culture") ?
        (requestContext.RouteData.Values["culture"].ToString().ToLower() == "en") : true;

}

I assume you want to default to English. 我假设你想要默认为英语。 If that's not the case, change : true; 如果不是这样,请更改: true; to : false; to : false;

See also Controller.Initialize method on MSDN. 另请参阅MSDN上的Controller.Initialize方法

尝试使用Action上的Viewbag返回使用_Layout.cshtml的View

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM