How to add css/script only to a Partial view?
c#, razor
Solution
You cannot load CSS and JavaScript resources specifically for a partial view without it applying to the entire page. Therefore, you'll need to design your page styles or JavaScript to target only the relevant sections.
<div id="header-section">
<ul class="menu">
...
<li>@Html.Partial("SearchHeader")</li>
</ul>
</div>
...
<div id="search-header">
<ul class="menu">...</ul>
</div>
If I wanted to style the `ul.menu` differently, I'd use selector rules
JavaScript
$("#header-section > .menu").css({ ... });
$("#search-header > .menu").css({ ... });
Or in a CSS file
#header-section > .menu { ... }
#search-header > .menu { ... }
Or just use distinct classes or specific ids
<div class="header-only"></div>
<div class="search-header-only"></div>
<div id="special-item"></div>
.header-only { font-size: 1em; }
.search-header-only { font-size: 0.85em; }
#special-item { font-size: 1.5em; }
Problem
I need to load css and scripts only to a specific Partial view but at this moment this link and scripts are loaded in all views. The structure that I have is the main view embedded a _Layout and Header, and the Header embedded a partial view called SearchHeader. ``` _Layout -> View <- Header <- SearchHeader ``` Header: ``` <li id="_Header_Menu"> <div> <ul class="sf-menu"> <li> @Html.Partial("../Home/SearchHeader") </li> </ul> </div> </li> ``` SearchHeader: ``` <html> <head> <link href="@Url.Content("~/Content/fonts")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("../../Content/GlyphIcons.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("../../Content/bootstrap.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("../../Content/bootstrap.min.css")" rel="stylesheet" type="text/css" /> </head> <body> <input type="text" name="contentToSearch" class="form-control" id="contentToSearch" placeholder="Search"> <script src="@Url.Content("../../Scripts/boostrap.min.js")" type="text/javascript"></script> <script src="@Url.Content("../../Scripts/jquery.js")" type="text/javascript"></script> </body> </html> ``` The css and scripts load correctly but there are applied to the `Header view`. How to only apply to the `SearchHeader view` ?