How to include js files in asp.net MVC and have a valid path on all routes

I created the default ASP.net project by default. On the main page, I have the following at the top

<head runat="server"> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> </head> 

Then I need to add the javascript file and add the line as follows by dragging the file from the solution browser to the page:

 <head runat="server"> <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title> <link href="../../Content/Site.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> </head> 

When I access the site and view the html from the browser, I see this:

 <head><title> Index </title><link href="Content/Site.css" rel="stylesheet" type="text/css" /> <script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script> </head> 

The relative path to the CSS file has been fixed, but the JS file is missing. The site will be deployed to a different folder on the server than the root that I get in my development window.

Is there any way to do this?

+6
javascript asp.net-mvc
source share
2 answers

Use the helper url:

 <script type="text/javascript" src="<%=Url.Content("~/Content/script/MyFile.js")%>"></script> 

Hope that helps

+16
source share

You can create a helper method that does something like this:

 <%= Helper.IncludeJavascriptFile("Menu.js") %> 

and then in this helper you do something like:

 public string IncludeJavascriptFile(string fileName){ return Url.Content("<root>/Javascript/Files/" + fileName); } 

You can then call this helper method from your view. If you decide to change the location of the files, then only in one place you will have to worry about it. If you change the file name, this is another problem in itself.

+7
source share

All Articles