Parameter setting path to jquery in mvc application

I am having trouble setting the jquery path in the mvc application. On my main page, I have a declared script and jquery in the root of my application. When I go to the content view page in my application, jquery does not load properly. Do I need to set the path on the content page or declare the path differently?

<script src="Views/Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
+3
source share
4 answers

The src on the main page is relative, which will not work on child pages. It should work if you declare the path as an absolute path (for example, "/Views/Scripts/jquery-1.2.6.min.js");

+2
source

, . Url.Content, :

<script src="<%= Url.Content("~/Content/jquery-1.2.6.min.js") %>" type="text/javascript"></script>
+11

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 referring to your script as follows:

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

Since you are on the main 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. So MasterPage, which comes from Control, can use it.

+1
source

All Articles