views:

1132

answers:

4

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>
+1  A: 

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

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

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>
Simon Steele
+1  A: 

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>
Todd Smith
+1  A: 

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.

labilbe