In MVC3 I can easily move the jQuery script tag to the bottom of the page "_Layout.vbhtml"
<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>
However in the ASP.NET MVC3 when you create a Controller with an editor template, the scaffolding mechanism does a good amount of work adding files to the Views folder like Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml etc... and they are strongly typed.
Inside those View files, script tags are inside the <body>
, but how can I add those tags to the bottom of the page immediately before </body>
tag?
What you are looking for is sections http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx
Add a section just above your </body>
tag.
@RenderSection("Scripts", false)
</body>
Then in your view you can define content that will appear in this section.
@section Scripts {
<script>
...
</script>
}
You can build an html extension function, like this
/// <summary>
/// This section is for adding a script to the <head> tag from a partial view (or any other place)
/// </summary>
private const string SCRIPTBLOCK_BUILDER = "_ScriptBlockBuilder_";
public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func<object, HelperResult> template)
{
htmlHelper.ViewContext.HttpContext.Items[SCRIPTBLOCK_BUILDER + Guid.NewGuid()] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith(SCRIPTBLOCK_BUILDER))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
Then you can use these two functions. In your _Layout.cshtml you put @Html.RenderScripts()
in the place you want to render all your scripts.
Then you wrap all your scripts in the view like this
@Html.Script(
@<script type="text/javascript">
// Your scripts
</script>
)
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