Is it possible to include a .js file in the View in asp.net mvc? I use razor engine, MVC 3.
It looks that header is already defined in _Layout.cshtml....So I pretty much have to include all my js files in the layout file?
2 Answers 2
You can define an optional section in your layout file. Then in your view define it.
_Layout.cshtml
<head>
..
@RenderSection("Includes", required: false)
..
</head>
In your view
@section Includes {
<script ...
}
4 Comments
Another way that can be used to organize and load javascript is using the following line in the Layout file.
<script src="@Url.Content("~/Scripts/ViewScripts/" +
ViewContext.RouteData.Values["controller"].ToString() + "." +
ViewContext.RouteData.Values["action"].ToString() + ".js")"
type="text/javascript"></script>
Then you can create separate js files for each controller action/view. For example, if you want to load a script specifically for your homepage using the default controller you create a file called home.index.js
or for the about page home.about.js
This gives a way to organize page specific javascript in small manageable files without having to specificallty load the script for every page. If the Controller/Action has a file it will be loaded, if it doesn't it will be skipped.