2

I am trying to load a javascript using the following in MVC 3, but the script does not load:

 <script src="<%: Url.Content("~/Content........

If I load using the following then it works:

<script src="../../Content......

What could be the problem

John Hartsock
  • 85,422
  • 23
  • 131
  • 146
Rama Desai
  • 39
  • 5

3 Answers3

2

When loading Scripts, I tend to use a custom helper instead.

The code below does this, and has an additional boolean parameter that can be used when the script is not local to your applicaiton, and on a CDN for instance.

    public static MvcHtmlString Script(this HtmlHelper helper, string src, bool local = true)
    {
        if (local) {
            src = VirtualPathUtility.ToAbsolute("~/Scripts/" + src);
        }
        TagBuilder builder = new TagBuilder("script");
        builder.MergeAttribute("src", src);
        builder.MergeAttribute("type", "text/javascript");
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));

    }

You can then call the helper in your view like this:

<%: Html.Script("jquery.validate.min.js") %>

or:

<%: Html.Script("http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js", false) %>
Nick
  • 1,116
  • 2
  • 12
  • 24
1

You should first Add an Assembly(namespace)

System.Web.Optimization

then simple render any Script like this.

@Scripts.Render("~/Content/Scripts/test.js")

do not forget to include namespace first

Using System.Web.Optimization;
syed Ahsan Jaffri
  • 1,160
  • 2
  • 14
  • 34
0

Note <%: renders an HTMLString and you do not want that. <%= renders a string. Below should work.

<script src="<%= Url.Content("~/Content........

see this question for details ASP.NET <%= %> vs <%: %>

Community
  • 1
  • 1
John Hartsock
  • 85,422
  • 23
  • 131
  • 146