I wrote an HtmlHelper for Javascript elements which, I believe, makes for a more maintainable codebase for adding script elements to a view:
public enum JavascriptPathType { Relative = 0, FullWebPath = 1 }; public static MvcHtmlString Script(this HtmlHelper helper, string jsFileName, JavascriptPathType pathType) { // Instantiate a UrlHelper var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); // Create tag builder var builder = new TagBuilder("script"); switch (pathType) { case JavascriptPathType.Relative: builder.MergeAttribute("src", urlHelper.Content("~/Scripts/" + jsFileName)); break; case JavascriptPathType.FullWebPath: builder.MergeAttribute("src", urlHelper.Content(jsFileName)); break; } // Add attributes builder.MergeAttribute("type", "text/javascript"); // Render tag. Note: script tags have to have an End tag and cannot be self-closing. return new MvcHtmlString(builder.ToString(TagRenderMode.Normal)); }
The most common scenario is where your javscript file is located in the Scripts directory of your project, in which case, all you need to do is pass in the name of the javascript file:
@Html.Script("jquery-1.8.2.min.js", JavascriptPathType.Relative);
This saves you from typing the script tags and the text type=”text/javascript” everytime.
I also added the custom enum JavascriptPathType to account for scenarios where the src of the script tag is pointing to someplace other than within your own project. For example, if you were using the Google maps API, the usage would be:
@Html.Script("http://maps.google.com/maps/api/js?sensor=false", JavascriptPathType.FullWebPath);
I’m thinking next will be the same kind of helper for Css files.