Note that there are some explanatory texts on larger screens.

plurals
  1. POPass arbitrary data from a partial view to the layout view
    primarykey
    data
    text
    <p><strong>Update</strong>: It seems I was trying to set the ViewBag content in a <em>partial</em> view instead in a <em>plain</em> view, MVC3 makes it very easy to do this. I'm still interested why it doesn't work for partial views, i.e. why isn't the viewbag shared with partial views.</p> <p>I'm trying to pass some data from a partial view to the layout view by using <code>ViewData</code>/<code>ViewBag</code></p> <pre><code>// Used in the partial view public static void RequireAssets(this HtmlHelper helper, params Asset[] assets) { var alreadyRequired = helper.ViewData["RequiredAssets"] as List&lt;Asset&gt;; if (alreadyRequired == null) { alreadyRequired = new List&lt;Asset&gt;(); helper.ViewData.Add("RequiredAssets", alreadyRequired); } foreach (var asset in assets.Where(anAsset =&gt; !alreadyRequired.Contains(anAsset))) alreadyRequired.Add(asset); } // Used in the layout view public static MvcHtmlString RenderAssetStyles(this HtmlHelper helper) { var requiredAssets = helper.ViewData["RequiredAssets"] as List&lt;Asset&gt;; return requiredAssets == null ? null : GetStyleSheets(requiredAssets.Select(e =&gt; new StyleSheet(e)).ToArray()); } public static MvcHtmlString RenderAssetScripts(this HtmlHelper helper) { var requiredAssets = helper.ViewData["RequiredAssets"] as List&lt;Asset&gt;; return requiredAssets == null ? null : GetScripts(requiredAssets.Select(e =&gt; new Script(e)).ToArray()); } </code></pre> <p>The problem is that when RenderAssetStyles/Scripts is fired in the layout view the <code>ViewData</code> does not contain the key "RequiredAssets"</p> <p><strong>Usage</strong></p> <p>_Layout.cshtml:</p> <pre><code>&lt;title&gt;@ViewBag.Title&lt;/title&gt; @Html.RenderAssetStyles() </code></pre> <p>PartialView.cshtml:</p> <pre><code>@{ Html.RequireAssets(Assets.Grid, Assets.FileUpload); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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