Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC3 how to move all scripts to the bottom of the page before </body>?

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?

like image 238
Max Avatar asked Sep 13 '25 10:09

Max


2 Answers

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>
}
like image 104
Ed Charbeneau Avatar answered Sep 15 '25 04:09

Ed Charbeneau


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>
)
like image 25
The Jonas Persson Avatar answered Sep 15 '25 03:09

The Jonas Persson