Pectus Excavatum
Pectus Excavatum

Reputation: 3773

.Net MVC how to add scripts to individual views

I was wondering if there is a way to add JavaScript files to individual views if I am using a wrapper .cshtml file.

Basically I have a wrapper cshtml file called _Layout that I am using for all my front end views. It basically has the <header> section and the HTML for my header/navigation and the footer. It also contains references to all the JavaScript files I need on each page after the footer.

However, on my contact view I want to use another JavaScript file, but I don't want to add it to the wrapper as that will add it to every single view.

Is there anyway to get add the file to the wrapper using a conditional statement - i.e. if Contact view then reference the contact JS file?

Upvotes: 5

Views: 6224

Answers (1)

johnnyRose
johnnyRose

Reputation: 7490

You can use Razor's section. It allows you to create "sections" in your layout page, and then add to them from your view pages.

You might already have a section "Scripts" declared in your layout page. If not, all you need to do is add @RenderSection("Scripts", required: false) in your layout, immediately after your other script tags. This creates a section called "Scripts" which we will add to later.

Then, you can add to that section by adding the following to your individual views:

@section Scripts {
    <script type="text/javascript" src="..."></script>
}

You can do this with other elements as well; you aren't limited only to scripts. You'll just have to add another @RenderSection("SectionName", required: false) to your layout page.

You might also be interested in reading Scott Gu's slightly dated (2010) blog post on Layouts and Sections with Razor.

Upvotes: 8

Related Questions