HtmlHelper for Javascript Script Elements (Tags)

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.

  1. Hi Dave,

    You should check on the new Bundling with MVC4. It’s pretty cool and even minifies your scripts if they aren’t minified already…

    http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

  2. Thanks Mike. I did not know that.

    Good to see MS add that feature. Telerik included that in its MVC extensions. And in the Webforms realm, a guy I worked with wrote an Asset Manager which does all that combining and minification. It’s a cool idea. An alternative might be to use something like Headjs which does parallel downloading of scripts.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>