Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The way I dealt with this is to write a couple extension methods to the HtmlHelper class. That allows partials views to say that they require a script, and then in the layout view that writes the tag I call to my helper method to emit the required scripts</p> <p>Here are the helper methods:</p> <pre><code>public static string RequireScript(this HtmlHelper html, string path, int priority = 1) { var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List&lt;ResourceInclude&gt;; if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = new List&lt;ResourceInclude&gt;(); if (!requiredScripts.Any(i =&gt; i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority }); return null; } public static HtmlString EmitRequiredScripts(this HtmlHelper html) { var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List&lt;ResourceInclude&gt;; if (requiredScripts == null) return null; StringBuilder sb = new StringBuilder(); foreach (var item in requiredScripts.OrderByDescending(i =&gt; i.Priority)) { sb.AppendFormat("&lt;script src=\"{0}\" type=\"text/javascript\"&gt;&lt;/script&gt;\n", item.Path); } return new HtmlString(sb.ToString()); } public class ResourceInclude { public string Path { get; set; } public int Priority { get; set; } } </code></pre> <p>Once you have that in place your partial view just needs to call <code>@Html.RequireScript("/Path/To/Script")</code>.</p> <p>And in the layout view's head section you call <code>@Html.EmitRequiredScripts()</code>.</p> <p>An added bonus of this is that it allows you to weed out duplicate script requests. If you have multiple views/partial views that need a given script you can safely assume that you will only output it once</p>
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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