Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @section scripts in a partial view MVC.Core

In ASP.NET Core MVC it is possible to define a script section for a page like this:

@section scripts {
    <script>
        alert('hello');
    </script>
}

And if the the layout contains :

@RenderSection("Scripts", required: false)

your script(s) will be rendered. This come in handy per example to guarantee that the scripts will be rendered after all javascript includes like jQuery.

But how to render a script in a partial view?

like image 819
Ivan Valadares Avatar asked Jul 07 '19 00:07

Ivan Valadares


1 Answers

Here is a solution :

In Layout page :

@Html.PageScripts()

In the Partial :

@using (Html.BeginScripts())
{
 <script>
   alert('hello');
 </script>
}

And The Helper Class for MVC.core

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.IO;

namespace MyProjectNamespace
{
    public static class HtmlHelpers
    {
        private const string ScriptsKey = "DelayedScripts";

        public static IDisposable BeginScripts(this IHtmlHelper helper)
        {
            return new ScriptBlock(helper.ViewContext);
        }

        public static HtmlString PageScripts(this IHtmlHelper helper)
        {
            return new HtmlString(string.Join(Environment.NewLine, GetPageScriptsList(helper.ViewContext.HttpContext)));
        }

        private static List<string> GetPageScriptsList(HttpContext httpContext)
        {
            var pageScripts = (List<string>)httpContext.Items[ScriptsKey];
            if (pageScripts == null)
            {
                pageScripts = new List<string>();
                httpContext.Items[ScriptsKey] = pageScripts;
            }
            return pageScripts;
        }

        private class ScriptBlock : IDisposable
        {
            private readonly TextWriter _originalWriter;
            private readonly StringWriter _scriptsWriter;

            private readonly ViewContext _viewContext;

            public ScriptBlock(ViewContext viewContext)
            {
                _viewContext = viewContext;
                _originalWriter = _viewContext.Writer;
                _viewContext.Writer = _scriptsWriter = new StringWriter();
            }

            public void Dispose()
            {
                _viewContext.Writer = _originalWriter;
                var pageScripts = GetPageScriptsList(_viewContext.HttpContext);
                pageScripts.Add(_scriptsWriter.ToString());
            }
        }
    }
}

Tip: import you class helper in _ViewImports.cshtml so you can use it in all views.

like image 151
Ivan Valadares Avatar answered Nov 08 '22 06:11

Ivan Valadares