Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

后端 未结 24 2011
无人共我
无人共我 2020-11-22 06:13

I have this section defined in my _Layout.cshtml

@RenderSection(\"Scripts\", false)

I can easily use it from a view:

24条回答
  •  暖寄归人
    2020-11-22 06:59

    You can use these Extension Methods: (Save as PartialWithScript.cs)

    namespace System.Web.Mvc.Html
    {
        public static class PartialWithScript
        {
            public static void RenderPartialWithScript(this HtmlHelper htmlHelper, string partialViewName)
            {
                if (htmlHelper.ViewBag.ScriptPartials == null)
                {
                    htmlHelper.ViewBag.ScriptPartials = new List();
                }
    
                if (!htmlHelper.ViewBag.ScriptPartials.Contains(partialViewName))
                {
                    htmlHelper.ViewBag.ScriptPartials.Add(partialViewName);
                }
    
                htmlHelper.ViewBag.ScriptPartialHtml = true;
                htmlHelper.RenderPartial(partialViewName);
            }
    
            public static void RenderPartialScripts(this HtmlHelper htmlHelper)
            {
                if (htmlHelper.ViewBag.ScriptPartials != null)
                {
                    htmlHelper.ViewBag.ScriptPartialHtml = false;
                    foreach (string partial in htmlHelper.ViewBag.ScriptPartials)
                    {
                        htmlHelper.RenderPartial(partial);
                    }
                }
            }
        }
    }
    

    Use like this:

    Example partial: (_MyPartial.cshtml) Put the html in the if, and the js in the else.

    @if (ViewBag.ScriptPartialHtml ?? true)
        

    I has htmls

    } else { }

    In your _Layout.cshtml, or wherever you want the scripts from the partials on to be rendered, put the following (once): It will render only the javascript of all partials on the current page at this location.

    @{ Html.RenderPartialScripts(); }
    

    Then to use your partial, simply do this: It will render only the html at this location.

    @{Html.RenderPartialWithScript("~/Views/MyController/_MyPartial.cshtml");}
    

提交回复
热议问题