Without knowing what ver of ASP.NET (or MVC) you are using, I can give you an easy way. You can always build a "helper" to do the heavy lifting for you. This is the way that MVC and ASP.NET 5 helpers handle it, but will work with just about any version. I generally don't prefer inline code, but a static helper can be made safe to protect against runtime errors.
First build a static helper utility:
public static class ScriptHelper
{
public static IHtmlString Render(params string[] paths)
{
return RenderFormat(DefaultTagFormat, paths);
}
public static IHtmlString RenderFormat(string tagFormat, params string[] paths)
{
if (string.IsNullOrEmpty(tagFormat))
{
throw new ArgumentException("Tag Format cannot be null");
}
if (paths == null)
{
throw new ArgumentNullException("Paths cannot be empty");
}
if (paths.Any(string.IsNullOrEmpty))
{
throw new ArgumentException("paths");
}
return BuildHtml(tagFormat, paths);
}
private static string defaultFormat = "<script src=\"{0}?ver={1}\"></script>";
public static string DefaultTagFormat
{
get
{
return defaultFormat;
}
set { defaultFormat = value; }
}
private static IHtmlString BuildHtml(string tagFormat, params string[] paths)
{
StringBuilder builder = new StringBuilder();
foreach (string path in paths)
{
StringBuilder builder = new StringBuilder();
foreach (string path in paths)
{
// Substitute your logic for version number
var version = "1234";
// You could factory this to a concrete type based on file extension etc.
var fileToOutPut = new VersionedJsFile(path,version,tagFormat);
builder.Append(fileToOutPut.RenderOutput());
builder.Append(Environment.NewLine);
}
return new HtmlString(builder.ToString());
}
}
You can add extra logic to wrap around the path, validation of path, virtual paths, etc. Best to create an object with a render method that you can pass in the path (from the helper) and the version. This is the oop way to do it and is more flexible. Doing that you can then have this be a "VersionHelper" instead and have it deal with css/js/etc.
internal abstract class HtmlFile
{
public abstract string RenderOutput();
}
internal class VersionedJsFile : HtmlFile
{
private string _version;
private string _path;
private string _format;
public VersionedJsFile(
string path,
string version,
string format)
{
if (version != null) _version = version;
if (path != null) _path = path;
if(!string.IsNullOrEmpty(format))
_format = format;
}
public override string RenderOutput()
{
if (!string.IsNullOrEmpty(_path)
&& !string.IsNullOrEmpty(_format))
{
string versionedFilePath = string.Format(_format, _path, _version);
return versionedFilePath;
}
return string.Empty;
}
}
Then add the helper to your page/master page/layout:
<%: ScriptHelper.Render("/scripts/bootstrap.js") %>
As you can see, the helper takes a params object so you can apply to multiple files at once.
Output:
<script src="/scripts/bootstrap.js?ver=1234"></script>
The helper can easily be enhanced.