Using ViewBag in Layout page

℡╲_俬逩灬. 提交于 2019-12-11 19:53:24

问题


I have my _Layout.cshtml file that uses the ViewBag model to render some dynamic content.

I understand ViewBag can be populated in the controller and accessed in the view and/or layout page.

My question is, if my Layout page is using @ViewBag.SiteName, I want to avoid having to set this variable in each controller before I return the view. Is there a way to set this variable on a global level? Or how else should I pass this data to the layout page?


回答1:


If you set anything in ViewBag - this happens after the Layout has been rendered - You've missed the boat.

As others have mentioned, you can create a "helper" controller:

public class LayoutController : BaseController
{
    [ChildActionOnly]
    public ActionResult SiteName()
    {
        return new ContentResult {Content = "Site name goes here"};
    }
}

Then, in your layout:

@{Html.Action("SiteName", "Layout")}


来源:https://stackoverflow.com/questions/26224790/using-viewbag-in-layout-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!