I created a default ASP.net MVC project. In the Master 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>
I then need to add a javascript file and added the line as follows by dragging the file from the solution explorer 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 a the site and look at 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 CSS file relative path was fixed but the JS file not. The site will be deployed to a different folder on the server than the root which I get on my development box.
Is there a proper way to do this?
Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.
The recommended approach is to put in a separate JavaScript file or inside a section defined in Layout page. A section can be added in the MVC Layout page using @RenderSection() directive. For example, we can define a section in Layout page under <head> tag for scripts like below.
JavaScript can be used in asp.net mvc.
Simply open the file in the browser, press "view source" and use the JS path in the URL to see if it opens. Your syntax is (more or less) correct.
Use the Url Helper:
<script type="text/javascript" src="<%=Url.Content("~/Content/script/MyFile.js")%>"></script>
Hope that helps
You can create a helper method that does something like this:
<%= Helper.IncludeJavascriptFile("Menu.js") %>
and then in that helper you do something like:
public string IncludeJavascriptFile(string fileName){
return Url.Content("<root>/Javascript/Files/" + fileName);
}
Then you can call that helper method from your view. If you decide to change the location of the files, it's only in one location you have to worry about it. If you change the name of the files, that's a different problem in and of itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With