1

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?

Control Freak
  • 12,965
  • 30
  • 94
  • 145
  • Please see if this helps! http://forums.asp.net/t/1820819.aspx?Global+ViewBag+Property – CodeMad Oct 06 '14 at 21:09
  • http://stackoverflow.com/questions/5453327/how-to-set-viewbag-properties-for-all-views-without-using-a-base-class-for-contr – CodeMad Oct 06 '14 at 21:09
  • You could create an action filter that sets the property, then apply the filter globally in `global.asax ` –  Oct 06 '14 at 21:10
  • I tried setting the `ViewBag.SiteName` in global.asax and it didn't work. – Control Freak Oct 06 '14 at 21:11
  • 1
    You could do this as a child action `@{Html.Action("SiteName", "Home");}` then have a `[ChildActionOnly]` action that returns a string. – Jasen Oct 06 '14 at 21:15
  • @ControlFreak, you may have misunderstood my comment. You set the property in a custom action filter then apply the filter to all controllers in `Application_Start()` of global.asax –  Oct 06 '14 at 21:38

1 Answers1

5

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")}
Alex
  • 37,502
  • 51
  • 204
  • 332
  • 1
    I call something like @{Html.Action("SiteName", "Layout")} in javascript and result is empty string. Example. var a=''@{Html.Action("SiteName", "Layout")}" , and a is empty string. When debugging method return string corretly but is empty inside view. – Vlado Pandžić Apr 15 '16 at 11:53
  • I know.It should be RenderAction in my case :) – Vlado Pandžić Apr 15 '16 at 11:55