I have a layout
page that has variables that need to be filled. Example:
@ModelType KarateAqua.schoolModel
<html>
<body>
@RenderBody()
<div id="footer">
<div class="content">
<div class="bottom_logo">
<a href="/"><span class="inv">@Model.schoolName</span></a>
</div>
</div>
</div>
</body>
</html>
I don't want to populate this in every ActionResult
. Is there a way to pass data to a layout
page once and do it for all instances?
Create an action filter and decorate your controller classes. Inside the action filter you have access to put values in the viewbag which are available to your layout.
This will run on each request and you will not have to set the values in each action. You can look for and ignore things like a child request and ajax requests which typically do not use the layout anyways and not set your viewbag values for those.
Below is a sample of an attribute i created to copy an object from the session and make it available to the layout via the ViewBag
You could use
ViewBag
orViewData
to pass data to your Layout pages.Layout
Controller
OK since you want this to be set once you can make use of a partial view. However depending on your needs you will need to have several partial views (may be not ideal if sections are going to be scattered across the _layout page)
your partial view will look like
Controller
in your _layout.cshtml place this line where you want to have the partial view to be inserted
You could always create action that returns a partial view of your header.
Just add this to your
layout
page:I used
HTTP Session
to persist the data between different pages -In the shared
_layout
page;Hope this helps but it won't work if you start from a different page from the default one that has been set.
You can open a code block on the layout page and fill the object there. This will execute every time the layout page is being used. The benefit is that you do not have to alter anything on your controller: