In a .NET MVC partial view, I’d like to do something like this:
<% ScriptCollection.RequireScript("path/to/script.js"); %>
That would require a method in the ScriptCollection object that looks like this:
public void RequireScript(string src)
{
if (!_List.Contains(src))
_List.Add(src);
}
Then, in my Master page, I would have something like this:
<html>
<head></head>
<body>
<!-- Content would go here -->
<% foreach (var script in ScriptCollection) { %>
<script type="text/javascript" src="<%= script %>"></script>
<% } %>
</body>
</html>
My question is this:
How can I make the ScriptCollection object available to be updated by a partial view and also available to be used by a Master page?
Edit:
I do not want to add the required scripts in a controller, nor do I want to use a strongly typed Master page. Though suggestions on doing so are welcome if those methods are considered a best practice.
Edit #2:
This would be easy with extension properties. I could just give the HtmlHelper class the ScriptCollection property. Am I missing something like this that already exists?
You could take a look at Telerik’s ScriptRegisterBuilder class implementation which does exactly what you want. Or you can just use it as well. In addition it also has support for:
Now even when you don’t use any of the other stuff Telerik provides you can use the
ScriptRegisterBuilderclass but then it’s advised to disable the automatic jquery & jquery validation script registration. See also the link provided.Also take a look the
StyleSheetRegistrarBuilderclass. This is the nephew of theScriptRegisterBuilderclass and handles the CSS assets.I did noticed the MVC2 tag in your question but my simple example uses razor and is just for making the point. It shouldn’t be hard to make it work for MVC2/ASPX as well. Otherwise let me know.
Master
Partial View