How do I inject a script tag such as
<script src="somejsfile"></script>
or
<script type="text/javascript>some javascript</script>
into the head tag of a page from a partial view?
Update: Answer for the old question This is about ASP.NET MVC. We can use the RenderSection. Here the sample for MVC 3 using Razor view engine:
layout view or master page:
<html>
<head>
<script ...></script>
<link .../>
@RenderSection("head")
</head>
<body>
...
@RenderBody()
...
</body>
</html>
View, e.g. Home:
@section head{
<!-- Here is what you can inject the header -->
<script ...></script>
@MyClass.GenerateMoreScript()
}
<!-- Here is your home html where the @RenderBody() located in the layout. -->
A Note About Script Binding for Partial ViewsJavaScript functions can be bound to elements on the partial view; the partial view is rendered at the same time as the parent view. This happens when loading the partial view with a @Html. Action helper method, as in this section from Edit.
Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .
A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.
On your layout page, if required is set to false : @RenderSection("scripts", required: false) , when the page renders and the user is on the about page, contacts. js won't render. If required is set to true : @RenderSection("scripts", required: true) , When page renders and user is on the About page, contacts.
Even if THX's answer works, it's not a good one as MVC's intention is to be stateless by nature. Moreover his solution does not let you place your scripts where they should go - most sites want their script declarations at the very bottom of their page just before the </body>
tag as it is best for performance and search engine optimization.
There is an answer, thanks to Darin Dimitrov:
Using sections in Editor/Display templates
His answer allows you to register scripts from a partial view within the layout view.
The caveat is his answer marks items using a GUID in a dictionary object, so there is no guarantee the scripts will be rendered in the master page in the same order they are listed in your partial view.
There are two workarounds for that:
I'm trying to work on the later myself.
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With