In a MVC3 project, I have a "_Layout.vbhtml" file with this code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
...
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
@RenderSection("Scripts", false)
</body>
</html>
Then, I have a Partial View "ValidationScripts.vbhtml" in the Shared folder with
@Section Scripts
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.fix.js")"></script>
<script src="@Url.Content("~/Scripts/localization/messages_de.js")"></script>
End Section
If I call the Partial View from a View like this...
@ModelType MvcExample.MyModel
@Code
ViewData("Title") = "Test"
End Code
@Html.Partial("ValidationScripts")
<h2>Just a Test</h2>
...
the Section "Scripts" is not rendered on the page, and the output HTML is
<!DOCTYPE html>
<html>
<head>
</head>
<body>
...
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")"></script>
</body>
</html>
How can I render the Section in the Partial View ?
all this was great info, however if you look at his original code, Section is capitalized therefore not being recognized.
it should be
@section
blahblah not@Section
If I understand correctly you have a structure
then you need to define the
@section Script{ .... }
in the View-X and NOT PartialView Y since View-X has itsView.Layout
set toLayout.cshtml
I had the same issue on top of duplicate scripts, so I created a couple of Extension methods:
On any View or Partial View or Display/Edit Template you simply add what you need:
In your Layouts you render it where you want it:
The only issue you may have is the order in which the scripts are rendered if you get to complex. If that becomes an issue, simply add the scripts to the bottom of your views/templates, and simply reverse the order in the extension method before rendering them.
You can't use sections in partial views. You can go for custom helpers as mentioned here.
I think you should be using helpers for this http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx
If you can upgrade to MVC4 you could use the new bundling and minification feature: http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification . It is specifically designed to address what you are trying to achieve (including scripts).
Alternatively you could use http://combres.codeplex.com/ with MVC3