ASP.NET MVC: place JavaScript from a View inside the head-section by using sections


When working with ASP.NET MVC, you often need some JavaScript in your views.
The most obvious way of doing this is just adding the JavaScript inside the view:

Your html source code will end up with a mess:

As you can see in the code above, the JavaScript was added where the your view was rendered.
To keep your code clean, you can use and render sections!

Open your master View _Layout.cshtml and add a RenderSection:

Now in your View (in my case /Home/About.cshtml) add the section:

Now your JavaScript will be injected inside the header:

That’s it! 🙂
You can add more logic to it, there is also an overload of the RenderSection in case you just want to say it is optional or not.

I demonstrated the RenderSection by injecting JavaScript into the header, but this can be used in other places (and you can also inject and render normal…

Ver la entrada original 16 palabras más



Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s

A %d blogueros les gusta esto: