Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
593 views
in Technique[技术] by (71.8m points)

asp.net mvc - Razor section inclusions from partial view

I have section for scripts in my _Layout.cshtml:

<html>
    <body>
    ...
        @RenderSection("FooterScript", required: false)
    </body>
</html>

I have view "Index.cshtml" that contains @Html.RenderPartial("LinksBlock", someModel). LinksBlock partial requires script file "links.js". I want to make links.js inclusion into FooterScript from my partial view, not from main view (main view don't know about dependencies of partial view), and I want to be sure, that if I use more than 1 LinksBlock in my view, only 1 links.js was included. Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sections do not work with partial views. But you could write a pair of custom helpers that could be used in conjunction:

public static class HtmlExtensions
{
    public static IHtmlString RegisteredScripts(this HtmlHelper htmlHelper)
    {
        var ctx = htmlHelper.ViewContext.HttpContext;
        var registeredScripts = ctx.Items["_scripts_"] as Stack<string>;
        if (registeredScripts == null || registeredScripts.Count < 1)
        {
            return null;
        }
        var sb = new StringBuilder();
        foreach (var script in registeredScripts)
        {
            var scriptBuilder = new TagBuilder("script");
            scriptBuilder.Attributes["type"] = "text/javascript";
            scriptBuilder.Attributes["src"] = script;
            sb.AppendLine(scriptBuilder.ToString(TagRenderMode.Normal));
        }
        return new HtmlString(sb.ToString());
    }

    public static void RegisterScript(this HtmlHelper htmlHelper, string script)
    {
        var ctx = htmlHelper.ViewContext.HttpContext;
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var registeredScripts = ctx.Items["_scripts_"] as Stack<string>;
        if (registeredScripts == null)
        {
            registeredScripts = new Stack<string>();
            ctx.Items["_scripts_"] = registeredScripts;
        }
        var src = urlHelper.Content(script);
        if (!registeredScripts.Contains(src))
        {
            registeredScripts.Push(src);
        }
    }
}

And then in your _Layout.cshtml:

@Html.RegisteredScripts()

and in your partial:

@{Html.RegisterScript("~/scripts/foo.js");}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...