Using scripts in a master page with ASP.NET MVC
Asked Answered
H

11

69

I'm fairly new to ASP.NET MVC, and I'm having a little trouble with scripts... in particular, I want to use jQuery in most pages, so it makes sense to put it in the master page. However, if I do (from my ~/Views/Shared/Site.Master):

<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>

Then that is literally what goes down to the client - which of course only works if our current route happens to have the right number of levels. Starting with ~/Scripts/... doesn't work. Starting with /Scripts/... would only work if the project was at the site root (which I don't want to assume).

I have one working approach (I'll post below) - but: am I missing something?

I'd rather not have to involve a script-manager, as that seems to defeat the simplicity of the ASP.NET MVC model... or am I worrying too much?

Here's the way I can get it working, which works also for non-trivial virtuals - but it seems over-complicated:

<script src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>" type="text/javascript"></script>
Hansiain answered 7/12, 2008 at 12:33 Comment(2)
The annoying thing about this, is that using the "~" prefix works fine for the href attribute of <link> elements, but not for the 'src' attribute of <script> elementsScour
@belugabob: What makes you say that this does not work in the src attribute of a script tag?Affection
A
45

I have a AppHelper class with some methods for adding script references:

public static string ReferenceScript(string scriptFile)
{
    var filePath = VirtualPathUtility.ToAbsolute("~/Scripts/" + scriptFile);
    return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}

so in your master page you can use:

<%= AppHelper.ReferenceScript("jquery-1.2.6.js") %>
Abby answered 7/12, 2008 at 13:21 Comment(3)
I like this; for the common API, I've now done something similar using an extension method on HtmlHelper, but +1Hansiain
Yeah, I really like extension methods but I created a lot of methods for referencing images, css and swf files. Not to overload HtmlHelper class y created AppHelper and add it's namespace to the web.configEczema
The use of HtmlHelper was just for likeness to a lot of other MVC codeHansiain
M
35

I think the simplest way is to use the following, and it works in views to.

<script type="text/javascript" src="<%=ResolveUrl("~/Scripts/myscript.js") %>">

</script>
Multiversity answered 2/7, 2009 at 4:36 Comment(2)
Why bother with any other method? This is the easiest and best.Rawinsonde
I'm in an agile production environment. Motto: if it works, good enough. If it lessens the amount of work i need to do, better. If its a 2 in 1, its great. this is great.Edmundedmunda
H
20

Based on the other replies, perhaps an extension method on Html (which is very common for MVC), similar to Eduardo's answer:

 <%=Html.Script("~/Scripts/jquery-1.2.6.js")%>

With:

public static string Script(this HtmlHelper html, string path)
{
    var filePath = VirtualPathUtility.ToAbsolute(path);
    return "<script type=\"text/javascript\" src=\"" + filePath + "\"></script>";
}
Hansiain answered 7/12, 2008 at 14:20 Comment(2)
I prefer not to have the path to the scripts in the views so if I have to move them to another domain or subdomain (or maybe a CDN) I don't have to touch every viewEczema
Fair comment - but in this case, it is a single master pageHansiain
W
10

Why not just point your master page at Google's js file hosting? Then even when it comes to deployment (assuming your site is Net facing) you can abuse possibly pre-cached jquery files?

Weave answered 7/12, 2008 at 12:43 Comment(3)
That assumes network access to Google, which isn't always the case... ideally it would work with just a local web-serverHansiain
Good approach for .com sites, but not necessarily good for intranet-style appsHansiain
Totally agree. This is purely an FYI in case :)Weave
A
4

I made some of what OJ mentions, I created a GoogleHelper class with this methods

public static string ReferenceGoogleAPI()
{
    var appSettings = new AppSettingsReader();
    string apiKey = appSettings.GetValue("GoogleApiKey", typeof(string)).ToString();
    return ReferenceGoogleAPI(apiKey);
}

public static string ReferenceGoogleAPI(string key)
{
    return "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi?key=" + key + "\"></script>";
}

public static string ReferenceGoogleLibrary(string name, string version)
{
    return "<script type=\"text/javascript\">google.load(\"" + name + "\", \"" + version + "\");</script>";
}

Now I'm adding extra methods to get some ClientLocation data ;)

Abby answered 7/12, 2008 at 13:37 Comment(0)
O
1

At work we are doing something like this from the ASP code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  Const jQuery As String = "jQuery"

  With Me.Page.ClientScript
    If Not .IsClientScriptIncludeRegistered(jQuery) Then
      .RegisterClientScriptInclude(jQuery, VirtualPathUtility.ToAbsolute("~/Includes/jQuery-1.2.6.js"))
    End If
  End With
End Sub

I don't know if it's possible to do that with ASP.NET MVC.

Ofori answered 16/1, 2009 at 10:19 Comment(1)
Nope, it isn't. MVC doesn't use the same approach. You could probably do something similar in the view, but there wouldn't be much purpose. By the way, I added notes re the GetHashCode question you asked earlier.Hansiain
I
1

ResolveUrl is the most elegant solution IMO. Though it's a real shame the urls to CSS are resolved by runat=server and not the script.

Infeasible answered 29/4, 2010 at 13:20 Comment(0)
O
1

You should take a look at using a utility like squish it. It can aggregate and obfuscate all of your css and js files for you. Or you can use it to generate script tags if you just keep it in debug more by using ForceDebug()

http://www.codethinked.com/squishit-the-friendly-aspnet-javascript-and-css-squisher

Outflow answered 14/12, 2011 at 18:59 Comment(0)
L
1

I just use a slash(/). For Example:

<script src="/Script/jquery-1.4.1.js"></script>

when the "jquery-1.4.1.js" file is in the Script directory of root. And it works perfectly.

Lelandleler answered 19/12, 2012 at 9:4 Comment(0)
P
0

Our applications are deployed using virtual directories, and we have had some issues with other answers mentioned here (not resolving the path correctly). One way that worked well, (not the only way mind you), was to use this:

<script src="<%=Request.ApplicationPath%>/Web/AppName/JavaScript/jquery-1.4.1.js"></script>
Parrie answered 12/8, 2010 at 23:43 Comment(1)
Sounds like it need to be wrapped up in a Url helper extension. That way you could use Url.Content or your version based on some config or a parameter, maybe...Brachial
T
0

You can try Url.Content extension method with Razor syntax

<script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
Tasty answered 31/8, 2012 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.