3

I am having trouble setting the path to jquery in an mvc app. In my master page I have the script declared and jquery works at the root of my app. When I navigate to a content view page in my app jquery does not get loaded properly. Do I need to set the path in the content page as well or declare the path differently?

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

4 Answers 4

11

While using an absolute path will work for some installations, you'll have problems when installing in sub-directories. A safer solution is to use Url.Content which will always resolve the path correctly:

<script src="<%= Url.Content("~/Content/jquery-1.2.6.min.js") %>" type="text/javascript"></script>
Sign up to request clarification or add additional context in comments.

Comments

2

The src on the masterpage is relative, which won't work on child pages. It should work if you declare the path as an absolute path (e.g. "/Views/Scripts/jquery-1.2.6.min.js");

2 Comments

This assumes that your app will always be installed in the site root. If it is installed in a subdirectory, it will not work.
Yes, of course. I was just trying to give him a nudge in the right direction.
1

I would suggest using a helper method

public static class Helper
{
    private static string ScriptsRoot = "~/views/scripts/";

    public static string ScriptUrl (string scriptFile)
    {
        return VirtualPathUtility.ToAbsolute (ScriptsRoot + scriptFile);
    }
}

And then referencing your script like this:

<script type="text/javascript" src="<%= Helper.ScriptUrl("jquery-1.2.6.min.js") %>"></script>

Comments

1

As you are on a master page you can use

<script src="<%=ResolveUrl(~/Views/Scripts/jquery-1.2.6.min.js) %>" type="text/javascript"></script>

ResolveUrl is a method inherited from Control. Thus, the MasterPage which derives from Control can use it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.