ASP.NET MVC Partial页输出JS

很多情况Partial是需要引用到JS的,通常做法是吧JS在引用Partial的页面中加入JS文件或者JS代码。

前阵子网上看到一段代码可以在Partial页面中添加JS,输出道引用页面。

  public static class HtmlExtensions
    {
        private const string JscriptDeferRazorViewdata = "__jsdfrz";
        private const string JscriptIncludeViewdata = "__jsrq";

        public static void DeferScript(this HtmlHelper html, string scriptLocation)
        {
            string jsTag = "<script type=\"text/javascript\" src=\"" + scriptLocation + "\"></script>";

            var jscripts = html.ViewContext.TempData[JscriptIncludeViewdata] as List<string> ?? new List<string>();
            if (!jscripts.Contains(jsTag))
            {
                jscripts.Add(jsTag);
            }
            html.ViewContext.TempData[JscriptIncludeViewdata] = jscripts;
        }

        public static MvcHtmlString Script(this HtmlHelper html, Func<int, HelperResult> script)
        {
            var jsActions = html.ViewContext.TempData[JscriptDeferRazorViewdata] as List<Func<int, HelperResult>> ?? new List<Func<int, HelperResult>>();
            jsActions.Add(script);
            html.ViewContext.TempData[JscriptDeferRazorViewdata] = jsActions;
            return MvcHtmlString.Empty;
        }

        public static IHtmlString RenderScripts(this HtmlHelper html)
        {
            var jscripts = html.ViewContext.TempData[JscriptIncludeViewdata] as List<string>;
            var jsActions = html.ViewContext.TempData[JscriptDeferRazorViewdata] as List<Func<int, HelperResult>>;
            html.ViewContext.TempData[JscriptIncludeViewdata] = new List<string>();
            html.ViewContext.TempData[JscriptDeferRazorViewdata] = new List<Func<int, HelperResult>>();
            return new HelperResult(writer =>
            {
                if (jscripts != null)
                {
                    writer.Write(string.Join("\r\n", jscripts.ToArray()));
                }
                if (jsActions != null) foreach (var action in jsActions) { action(0).WriteTo(writer); }
            });
        }
    }

在引用Partial的页面中添加:

@section scripts{
    @Html.RenderScripts()
}

Partial页面:

@{
    Html.Script(
        @<script type="text/javascript">
          //再此些你的JS代码
         </script>
        );
   Html.DeferScript("//再此引用你的JS文件");
}
作者:guozx 出处:http://www.cnblogs.com/Innovate/ 声明:原创文字只代表本人某一时间内的观点或结论,本人不对涉及到的任何代码担保。转载请标明出处!
原文地址:https://www.cnblogs.com/Innovate/p/5465196.html