Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I found a need to do this in my own project, because I wanted to be able to have a separate javascript\css file for each view.</p> <p>What I ended up doing was creating a controller to aggregate the files on the server for me and then send only one css\js file to the browser. The answer is perhaps more intricate than you requested though, so I'll recommend the first part.</p> <p>You can make an extension method that you can call at the top of each page to add a JS file to a list in the TempData dictionary for the request. You then call a separate method from the Layout that will render any additional links.</p> <p>This works because the TempData is kept just for the request, and the layout's View is rendered last (after all the views and partials run).</p> <p>I have a full example of a class here: <a href="http://pastebin.com/EUC2fAca" rel="nofollow">http://pastebin.com/EUC2fAca</a> but i'm also forming links to my aggregator, so you'll need to modify. The gist is as follows:</p> <pre><code>public static string JSKey = "pageJSList"; private static void AddToDictionary(HtmlHelper helper, string[] files, string key) { if (files == null || files.Length == 0) return; TempDataDictionary dict = helper.ViewContext.TempData; if (!dict.ContainsKey(key)) dict.Add(key, new List&lt;string&gt;()); (dict[key] as List&lt;string&gt;).AddRange(files); } private static void InsertToDictionary(HtmlHelper helper, string[] files, string key) { if (files == null || files.Length == 0) return; TempDataDictionary dict = helper.ViewContext.TempData; if (!dict.ContainsKey(key)) dict.Add(key, new List&lt;string&gt;()); (dict[key] as List&lt;string&gt;).InsertRange(0, files); } public static void AddJS(this HtmlHelper helper, params string[] files) { AddToDictionary(helper, files, JSKey); } public static void AddJSToTop(this HtmlHelper helper, params string[] files) { InsertToDictionary(helper, files, JSKey); } public static MvcHtmlString GetJsTagHtml(HtmlHelper helper) { var files = helper.ViewContext.TempData[JSKey] as List&lt;string&gt;; StringBuilder tags = new StringBuilder(); string jsTemplate = "&lt;script type=\"text/javascript\" src=\"/Scripts/{0}\"&gt;&lt;/script&gt;"; foreach (string file in files) { tags.AppendLine(String.Format(jsTemplate, file)); } return MvcHtmlString.Create(tags.ToString()); } </code></pre> <p>You'll want the Insert method to run it on the layout because, again, it runs last so you'll want to Insert jquery libraries or other dependencies that should be first on the list.</p> <p>Your GetJS method should probably return an MvcHtmlString that contains all of the tags you need.</p> <p>Hope that helps and wasn't too long winded =)</p>
 

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