Note that there are some explanatory texts on larger screens.

plurals
  1. POASP.NET MVC - Set variable in layout template from partial or body
    text
    copied!<h2>Question</h2> <p>In ASP.NET MVC (and specifically with Razor), how does one set the value of a variable within a partial (or "sub-template") and access that value within a master (or layout) template?</p> <h2>Goal</h2> <p>I would like to maintain lists of assets (stylesheets and JavaScript files) and be able to add to the lists from within partials. The assets should then be accessible within the master layout to be included in the <code>&lt;head/&gt;</code> (stylesheets) or near the end of the <code>&lt;body/&gt;</code> (JavaScript files) of the page. This provides an elegant means of storing modules in partials that include all necessary assets.</p> <h2>My Attempt</h2> <p>Below is what I have tried for stylesheets. The intended result is that both <code>global.css</code> and <code>view_post.css</code> would be included in the header, but only <code>global.css</code> is showing up. It is my understanding that this occurs because the layout is rendered before the template.</p> <h3>Helpers/AssetHelper.cs</h3> <pre><code>namespace MyApp.Helpers { public static class AssetHelper { private static SortedSet&lt;string&gt; StyleSheets(this HtmlHelper helper) { if (helper.ViewBag._styleSheets == null) helper.ViewBag._styleSheets = new SortedSet&lt;string&gt; (); return helper.ViewBag._stylesheets as SortedSet&lt;string&gt;; } public static MvcHtmlString AddStyleSheet(this HtmlHelper helper, string styleSheet) { helper.StyleSheets().Add(styleSheet); return new MvcHtmlString(""); } public static MvcHtmlString RenderStyles(this HtmlHelper helper) { StringBuilder output = new StringBuilder(); string template = "&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" /&gt;"; foreach (string styleSheet in helper.StyleSheets()) output.Append(String.Format(template, styleSheet)); return new MvcHtmlString(output.ToString()); } } } </code></pre> <h3>Views/Shared/Layout.cshtml</h3> <pre><code>@using MyApp.Helpers &lt;html&gt; &lt;head&gt; ... @Html.AddStyleSheet("global.css") @Html.RenderStyles() &lt;/head&gt; &lt;body&gt; ... @RenderBody ... &lt;/body&gt; &lt;/html&gt; </code></pre> <h3>Views/Posts/View.cshtml</h3> <pre><code>@using MyApp.Helpers @Html.AddStyleSheet("view_post.css") &lt;h2&gt;...&lt;/h2&gt; &lt;p&gt;...&lt;/p&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload