Take the 2-minute tour ×

I want to include a javascript reference like:

<script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script>

If I have a Razor View, what is the proper way to include this without having to add it to the Layout (I only need it in a single specific View, not all of them)

In aspx, we could use content place holders.. I found older examples using aspx in mvc but not Razor view..

share|improve this question
You just did it? –  Brad Christie Jan 11 '13 at 18:49
Just add the script tag to your view. –  jrummell Jan 11 '13 at 18:54
I just want to add the script in my view, but when i view source on the page that gets created, it puts the script tags inside the <body> of the html instead of the <head> ? –  dferraro Jan 11 '13 at 19:03
add comment

1 Answer

up vote 5 down vote accepted

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.


<!DOCTYPE html>


@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

share|improve this answer
BTW, sections are essentially your contentplaceholders you were referring to. See the default MVC web project and how they place a heading on the page. –  Brad Christie Jan 11 '13 at 18:57
thanks. This was what I was looking for - but is it possible to do this without the RenderSection? You say 'what you have is fine' - but I don't have anything yet... I tried putting the script references at the top of the .cshtml, but the result is the references are in the <body> but they should be in the head –  dferraro Jan 11 '13 at 19:04
@dferraro: then you need to add RenderSection("Scripts") to your layout (like you would a placeholder) and then define a @section Scripts {} within the view. At some point a modification to the "master" (_layout) is imminent. You can't just define something within a view and tell it "place it between <head> for me" (unless you want to get in to a script that adds a script) –  Brad Christie Jan 11 '13 at 19:06
+1. Also @dferraro a better thing would be to put the references to jQuery and the RenderSection before the </body> and not in the head at all. Old but relevant reading: developer.yahoo.com/blogs/ydn/posts/2007/07/high_performanc_5 –  MikeSmithDev Jan 11 '13 at 19:15
add comment

Your Answer


