最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - .Net MVC how to add scripts to individual views - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Nov 28, 2015 at 16:28 GrandMasterFlush 6,40919 gold badges85 silver badges109 bronze badges asked Nov 28, 2015 at 16:15 Pectus ExcavatumPectus Excavatum 3,78518 gold badges51 silver badges69 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论