Reputation: 37633
How to add link to JavaScript file into the header of the certain ASP .NET MVC page?
Lets say there are _Layout.cshtml and About.cshtml and I need to put some javascript file to the header of the About.cshtml. I mean to that page only.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=636
How it can be done?
Upvotes: 3
Views: 6676
Reputation: 2064
Try below code
HtmlGenericControl my_js = new HtmlGenericControl("script");
my_js.Attributes["async"] = "async";
my_js.Attributes["type"] = "text/javascript";
my_js.Attributes["src"] = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js";
Page.Header.Controls.Add(my_js);
You need to use namespace : "using System.Web.UI.HtmlControls" to use HtmlGenericControl.
Upvotes: 1
Reputation: 37633
My solution:
_Layout.cshtml
!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
@if (IsSectionDefined("AddToHead"))
{
@RenderSection("AddToHead", required: false)
}
</head>
About.cshtml
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@section footer {
<b>Footer Here</b>
}
@section AddToHead {
<script src="@Url.Content("~/Scripts/test.js")" type="text/javascript">
</script>
}
Upvotes: 4
Reputation: 82267
Why must it be in the header? You can include any script you need inline:
<script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>
Upvotes: 4