简体   繁体   中英

How to Set ViewBag Properties for _Layout.cshtml

I am trying to pass a ViewBag property to customize html in _Layout.cshtml.

@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. I thought _Layout is executed by the ViewEngine, and ViewEngine runs after Controllers have run. Where should I place my ViewBag initialization code so that it becomes available to _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; to : false;

See also Controller.Initialize method on MSDN.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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