Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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?

like image 741
Pectus Excavatum Avatar asked Nov 28 '15 16:11

Pectus Excavatum


People also ask

Can I add script inside body?

JavaScript in <head> or <body> You can place any number of scripts in an HTML document. Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

How do you add a script section in partial view?

Add(new ScriptBundle("~/bundles/CustomScripts"). Include( "~/Scripts/Custom/partial-view. js" )); Load the custom script bundle like any other bundle in your layout.

How do I add a script to Razor view?

Calling JavaScript Function from Razor View To include a JavaScript function, it is as simple as include a <script> tag and define the function inside the script block. Now, to call the function, add an onclick event on the employee name hyperlink and call the function.

Can we add script in partial view in MVC?

Mvc and System. Web. Mvc. Ajax namespaces can be combined with JavaScript and MVC partial views to create flexible interactive web pages with minimal code.


1 Answers

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.

like image 195
johnnyRose Avatar answered Oct 02 '22 02:10

johnnyRose