Using ViewBag in Layout page

2019-09-04 05: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条回答
祖国的老花朵
2楼-- · 2019-09-04 05:47

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")}
查看更多
登录 后发表回答