Populate a Razor Section From a Partial

前端 未结 12 1466
不知归路
不知归路 2020-11-27 11:23

My main motivation for trying to do this is to get Javascript that is only required by a partial at the bottom of the page with the rest of the Javascript and not in the mid

相关标签:
12条回答
  • 2020-11-27 11:58

    [Updated version] Updated version following @Necrocubus question to Include inline scripts.

    public static class ScriptsExtensions
    {
        const string REQ_SCRIPT = "RequiredScript";
        const string REQ_INLINESCRIPT = "RequiredInlineScript";
        const string REQ_STYLE = "RequiredStyle";
    
        #region Scripts
        /// <summary>
        /// Adds a script 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="path"></param>
        /// <param name="priority">Ordered by decreasing priority </param>
        /// <param name="bottom"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static string RequireScript(this IHtmlHelper html, string path, int priority = 1, bool bottom=false, params string[] options)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceToInclude>;
            if (requiredScripts == null) ctxt.Items[REQ_SCRIPT] = requiredScripts = new List<ResourceToInclude>();
            if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceToInclude() { Path = path, Priority = priority, Options = options, Type=ResourceType.Script, Bottom=bottom});
            return null;
        }
    
        /// <summary>
        /// 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="script"></param>
        /// <param name="priority">Ordered by decreasing priority </param>
        /// <param name="bottom"></param>
        /// <returns></returns>
        public static string RequireInlineScript(this IHtmlHelper html, string script, int priority = 1, bool bottom = false)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_INLINESCRIPT] as List<InlineResource>;
            if (requiredScripts == null) ctxt.Items[REQ_INLINESCRIPT] = requiredScripts = new List<InlineResource>();
            requiredScripts.Add(new InlineResource() { Content=script, Priority = priority, Bottom=bottom, Type=ResourceType.Script});
            return null;
        }
    
        /// <summary>
        /// Just call @Html.EmitRequiredScripts(false)
        /// at the end of your head tag and 
        /// @Html.EmitRequiredScripts(true) at the end of the body if some scripts are set to be at the bottom.
        /// </summary>
        public static HtmlString EmitRequiredScripts(this IHtmlHelper html, bool bottom)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceToInclude>;
            var requiredInlineScripts = ctxt.Items[REQ_INLINESCRIPT] as List<InlineResource>;
            var scripts = new List<Resource>();
            scripts.AddRange(requiredScripts ?? new List<ResourceToInclude>());
            scripts.AddRange(requiredInlineScripts ?? new List<InlineResource>());
            if (scripts.Count==0) return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in scripts.Where(s=>s.Bottom==bottom).OrderByDescending(i => i.Priority))
            {
                sb.Append(item.ToString());
            }
            return new HtmlString(sb.ToString());
        }
        #endregion Scripts
    
        #region Styles
        /// <summary>
        /// 
        /// </summary>
        /// <param name="html"></param>
        /// <param name="path"></param>
        /// <param name="priority">Ordered by decreasing priority </param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static string RequireStyle(this IHtmlHelper html, string path, int priority = 1, params string[] options)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceToInclude>;
            if (requiredScripts == null) ctxt.Items[REQ_STYLE] = requiredScripts = new List<ResourceToInclude>();
            if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceToInclude() { Path = path, Priority = priority, Options = options });
            return null;
        }
    
        /// <summary>
        /// Just call @Html.EmitRequiredStyles()
        /// at the end of your head tag
        /// </summary>
        public static HtmlString EmitRequiredStyles(this IHtmlHelper html)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceToInclude>;
            if (requiredScripts == null) return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
            {
                sb.Append(item.ToString());
            }
            return new HtmlString(sb.ToString());
        }
        #endregion Styles
    
        #region Models
        public class InlineResource : Resource
        {
            public string Content { get; set; }
            public override string ToString()
            {
                return "<script>"+Content+"</script>";
            }
        }
    
        public class ResourceToInclude : Resource
        {
            public string Path { get; set; }
            public string[] Options { get; set; }
            public override string ToString()
            {
                switch(Type)
                {
                    case ResourceType.CSS:
                        if (Options == null || Options.Length == 0)
                            return String.Format("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" />\n", Path);
                        else
                            return String.Format("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" {1} />\n", Path, String.Join(" ", Options));
                    default:
                    case ResourceType.Script:
                        if (Options == null || Options.Length == 0)
                            return String.Format("<script src=\"{0}\" type=\"text/javascript\"></script>\n", Path);
                        else
                            return String.Format("<script src=\"{0}\" type=\"text/javascript\" {1}></script>\n", Path, String.Join(" ", Options));
                }
            }
        }
        public class Resource
        {
            public ResourceType Type { get; set; }
            public int Priority { get; set; }
            public bool Bottom { get; set; }
        }
        public enum ResourceType
        {
            Script,
            CSS
        }
        #endregion Models
    }
    

    My 2 cents, it is an old post, but still relevant, so here is an upgraded update of Mr Bell's solution which works with ASP.Net Core.

    It allows adding scripts and styles to the main layout from imported partial views and subviews, and possibility to add options to script/style imports (like async defer etc):

    public static class ScriptsExtensions
    {
        const string REQ_SCRIPT = "RequiredScript";
        const string REQ_STYLE = "RequiredStyle";
    
        public static string RequireScript(this IHtmlHelper html, string path, int priority = 1, params string[] options)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceInclude>;
            if (requiredScripts == null) ctxt.Items[REQ_SCRIPT] = requiredScripts = new List<ResourceInclude>();
            if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority, Options = options });
            return null;
        }
    
    
        public static HtmlString EmitRequiredScripts(this IHtmlHelper html)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceInclude>;
            if (requiredScripts == null) return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
            {
                if (item.Options == null || item.Options.Length == 0)
                    sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
                else
                    sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\" {1}></script>\n", item.Path, String.Join(" ", item.Options));
    
            }
            return new HtmlString(sb.ToString());
        }
    
    
        public static string RequireStyle(this IHtmlHelper html, string path, int priority = 1, params string[] options)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceInclude>;
            if (requiredScripts == null) ctxt.Items[REQ_STYLE] = requiredScripts = new List<ResourceInclude>();
            if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority, Options = options });
            return null;
        }
    
    
        public static HtmlString EmitRequiredStyles(this IHtmlHelper html)
        {
            var ctxt = html.ViewContext.HttpContext;
    
            var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceInclude>;
            if (requiredScripts == null) return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
            {
                if (item.Options == null || item.Options.Length == 0)
                    sb.AppendFormat("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" />\n", item.Path);
                else
                    sb.AppendFormat("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" {1} />\n", item.Path, String.Join(" ", item.Options));
            }
            return new HtmlString(sb.ToString());
        }
    
    
        public class ResourceInclude
        {
            public string Path { get; set; }
            public int Priority { get; set; }
            public string[] Options { get; set; }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 11:58

    Here cames my solution to the frequently asked questions "how to inject sections from partial views to main views or main layout view for asp.net mvc?". If you do a search on stackoverflow by keywords "section + partial", you will get quite a big list of related questions, and given answers, but none of them are seems elegant to me by means of the razor engine grammar. So I just take a look to the Razor engine see if there could be a some better solution to this question.

    Fortunately, I found something it is interesting to me of how the Razor engine does the compilation for the view template file (*.cshtml, *.vbhtml). (I will explain later), below is my code of the solution which I think is quite simple and elegant enough in usage.

    namespace System.Web.Mvc.Html
    {
        public static class HtmlHelperExtensions
        {
            /// <summary>
            /// 确保所有视图,包括分部视图(PartialView)中的节(Section)定义被按照先后顺序追加到最终文档输出流中
            /// </summary>
            public static MvcHtmlString EnsureSection(this HtmlHelper helper)
            {
                var wp = (WebViewPage)helper.ViewDataContainer;
                Dictionary<string, WebPages.SectionWriter> sw = (Dictionary<string, WebPages.SectionWriter>)typeof(WebPages.WebPageBase).GetProperty("SectionWriters", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance).GetValue(wp);
                if (!helper.ViewContext.HttpContext.Items.Contains("SectionWriter"))
                {
                    Dictionary<string, Stack<WebPages.SectionWriter>> qss = new Dictionary<string, Stack<WebPages.SectionWriter>>();
                    helper.ViewContext.HttpContext.Items["SectionWriter"] = qss;
                }
                var eqs = (Dictionary<string, Stack<WebPages.SectionWriter>>)helper.ViewContext.HttpContext.Items["SectionWriter"];
                foreach (var kp in sw)
                {
                    if (!eqs.ContainsKey(kp.Key)) eqs[kp.Key] = new Stack<WebPages.SectionWriter>();
                    eqs[kp.Key].Push(kp.Value);
                }
                return MvcHtmlString.Create("");
            }
    
            /// <summary>
            /// 在文档流中渲染指定的节(Section)
            /// </summary>
            public static MvcHtmlString RenderSectionEx(this HtmlHelper helper, string section, bool required = false)
            {
                if (helper.ViewContext.HttpContext.Items.Contains("SectionWriter"))
                {
                    Dictionary<string, Stack<WebPages.SectionWriter>> qss = (Dictionary<string, Stack<WebPages.SectionWriter>>)helper.ViewContext.HttpContext.Items["SectionWriter"];
                    if (qss.ContainsKey(section))
                    {
                        var wp = (WebViewPage)helper.ViewDataContainer;
                        var qs = qss[section];
                        while (qs.Count > 0)
                        {
                            var sw = qs.Pop();
                            var os = ((WebViewPage)sw.Target).OutputStack;
                            if (os.Count == 0) os.Push(wp.Output);
                            sw.Invoke();
                        }
                    }
                    else if (!qss.ContainsKey(section) && required)
                    {
                        throw new Exception(string.Format("'{0}' section is not defined.", section));
                    }
                }
                return MvcHtmlString.Create("");
            }
        }
    }
    

    usage: To use the code is quite simple as well, and it looks almost the same style to the usual. It also supports any levels to the nested partial views. ie. I have a view template chain: _ViewStart.cshtml->layout.cshtml->index.cshtml->[head.cshtml,foot.cshtml]->ad.cshtml.

    In layout.cshtml, we have:

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>@ViewBag.Title - @ViewBag.WebSetting.Site.WebName</title>
        <base href="@ViewBag.Template/" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta http-equiv="Cache-Control" content="no-siteapp" />
        <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1.0, user-scalable=0,user-scalable=no">
        <meta name="format-detection" content="telephone=no">
        <meta name="renderer" content="webkit">
        <meta name="author" content="Taro Technology Co.,LTD" />
        <meta name="robots" content="index,follow" />
        <meta name="description" content="" />
        <meta name="keywords" content="" />
        <link rel="alternate icon" type="@ViewBag.WebSetting.Site.WebFavIcon" href="@ViewBag.WebSetting.Site.WebFavIcon">
        @Html.RenderSectionEx("Head")
    </head>
    <body>
        @RenderBody()
        @Html.RenderSectionEx("Foot")
    </body>
    </html>

    And in index.cshtml, we have:

    @{
        ViewBag.Title = "首页";
    }
    
    @Html.Partial("head")
    <div class="am-container-1">
        .......
    </div>
    @Html.Partial("foot")

    And in head.cshtml, we would have the code:

    @section Head{
        <link rel="stylesheet" href="assets/css/amazeui.css" />
        <link rel="stylesheet" href="assets/css/style.css" />
    }
    
    <header class="header">
       ......
    </header>
    @Html.EnsureSection()

    it is the same in foot.cshtml or ad.cshtml, you can still define Head or Foot section in them, make sure to call @Html.EnsureSection() once at the end of the partial view file. That's all you need to do to get rid of the subjected issue in asp mvc.

    I just share my code snippet so others may take use of it. If you feel it is useful, please don't hesitate to up rate my post. :)

    0 讨论(0)
  • 2020-11-27 12:01

    For those looking for the aspnet core 2.0 version:

        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using Microsoft.AspNetCore.Html;
        using Microsoft.AspNetCore.Http;
    
        public static class HttpContextAccessorExtensions
        {
            public static string RequireScript(this IHttpContextAccessor htmlContextAccessor, string path, int priority = 1)
            {
                var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List<ResourceInclude>;
                if (requiredScripts == null) htmlContextAccessor.HttpContext.Items["RequiredScripts"] = requiredScripts = new List<ResourceInclude>();
                if (requiredScripts.All(i => i.Path != path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
                return null;
            }
    
            public static HtmlString EmitRequiredScripts(this IHttpContextAccessor htmlContextAccessor)
            {
                var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List<ResourceInclude>;
                if (requiredScripts == null) return null;
                StringBuilder sb = new StringBuilder();
                foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
                {
                    sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
                }
                return new HtmlString(sb.ToString());
            }
            public class ResourceInclude
            {
                public string Path { get; set; }
                public int Priority { get; set; }
            }
        }
    

    Add to your layout after the scripts render section call:

    @HttpContextAccessor.EmitRequiredScripts()
    

    And in your partial view:

    @inject IHttpContextAccessor HttpContextAccessor
    
    ...
    
    @HttpContextAccessor.RequireScript("/scripts/moment.min.js")
    
    0 讨论(0)
  • 2020-11-27 12:02

    Install the Forloop.HtmlHelpers nuget package - it adds some helpers for managing scripts in partial views and editor templates.

    Somewhere in your layout, you need to call

    @Html.RenderScripts()
    

    This will be where any script files and script blocks will be outputted in the page so I would recommend putting it after your main scripts in the layout and after a scripts section (if you have one).

    If you're using The Web Optimization Framework with bundling, you can use the overload

    @Html.RenderScripts(Scripts.Render)
    

    so that this method is used for writing out script files.

    Now, anytime you want to add script files or blocks in a view, partial view or template, simply use

    @using (Html.BeginScriptContext())
    {
      Html.AddScriptFile("~/Scripts/jquery.validate.js");
      Html.AddScriptBlock(
        @<script type="text/javascript">
           $(function() { $('#someField').datepicker(); });
         </script>
      );
    }
    

    The helpers ensure that only one script file reference is rendered if added multiple times and it also ensures that script files are rendered out in an expected order i.e.

    1. Layout
    2. Partials and Templates (in the order in which they appear in the view, top to bottom)
    0 讨论(0)
  • 2020-11-27 12:03

    Partial views cannot participate in their parent views' sections.

    0 讨论(0)
  • 2020-11-27 12:05

    You can create a new Layout page and wrap the PartialView inside of a Full View that is responsible for rendering the contents and also any library sections.

    For example, let's say I have the following code:

    HomeController.cs

    [HttpGet]
    public ActionResult About()
    {
        var vm = new AboutViewModel();
        return View("About", vm);
    }
    

    When the Full Page view is rendered, it's typically renderedby merging two files:

    About.cshtml

    @model AboutViewModel
    
    @{
        ViewBag.Title = "About CSHN";
    }
    
    <h3>@ViewBag.Title</h3>
    
    @section Styles {
        <style> /* style info here */ </style>
    }
    
    @section Scripts {
        <script> /* script info here */ </script>
    }
    

    _Layout.cshtml (or whatever is specified in _ViewStart or overridden in the page)

    <!DOCTYPE html>
    
    <html>
    <head>
        @RenderSection("Styles", false)
        <title>@ViewBag.Title</title>
    </head>
    <body>
        @RenderBody()
    
        @RenderSection("scripts", false)
    </body>
    </html>
    

    Now, suppose you wanted to Render About.cshtml as a Partial View, perhaps as modal window in response to AJAX call. The goal here being to return only the content specified in the about page, scripts and all, without all the bloat included in the _Layout.cshtml master layout (like a full <html> document).

    You might try it like this, but it won't come with any of the section blocks:

    return PartialView("About", vm);
    

    Instead, add a simpler layout page like this:

    _PartialLayout.cshtml

    <div>
        @RenderBody()
        @RenderSection("Styles", false)
        @RenderSection("scripts", false)
    </div>
    

    Or to support a modal window like this:

    _ModalLayout.cshtml

    <div class="modal modal-page fade" tabindex="-1" role="dialog" >
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
    
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">@ViewBag.Title</h4>
                </div>
    
                <div class="modal-body">
    
                    @RenderBody()
                    @RenderSection("Styles", false)
                    @RenderSection("scripts", false)
    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-inverse" data-dismiss="modal">Dismiss</button>
                </div>
            </div>
        </div>
    </div>
    

    Then you can specify a custom Master View in this controller or any other handler that you want to render the contents and scripts of a view simultaneously

    [HttpGet]
    public ActionResult About()
    {
        var vm = new AboutViewModel();
        return !Request.IsAjaxRequest()
                  ? View("About", vm)
                  : View("About", "~/Views/Shared/_ModalLayout.cshtml", vm);
    }
    
    0 讨论(0)
提交回复
热议问题