ASP.NET MVC Partial页输出JS

2016-05-06 12:44
分类:编程  ASP.NET  
作者:Zhengxing

很多情况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文件");
}

 

好文要顶 收藏该文 我要举报
如果您觉得本文对你有用,不妨帮忙点个赞,或者在评论里给我一句赞美,小小成就都是今后继续为大家编写优质文章的动力!
上一篇:CodeSnippet.info 开源说明 和 环境搭建 (第一版)
下一篇:C#开发微信门户及应用(4)--关注用户列表及详细信息管理

一起悦读网    Copyright © 2016    浙ICP备11048508号