Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
368 views
Welcome To Ask or Share your Answers For Others

1 Answer

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") %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...