也說 ASP.NET MVC的 Script 管理


WebForm下的ScriptManager在ASP.NET MVC下自然是不能使用的。於是很多人開始困惑如何管理頁面上可能發生衝突的腳本。CodePlex上還有一個項目專門做這件事情,當然也有人簡單地通過HtmlHelper來解決。如果你看過jQuery UI Extensions for ASP.NET MVC,或者是jQuery Grid for ASP.NET MVC,你還會找到更多的解決方案。總體上講,這些解決方案的特點是:
1.用一個詞典管理已經註冊的腳本項,最後再一次性生成所有註冊的腳本。所以,你不能漏了在masterpage的bady的最後運行腳本生成。
2.腳本在頁面的body區而不是head區。
思考半天,感覺複雜了一點。我的解決方案比較簡單,每次註冊腳本調用一個擴展足夠了。

代碼
public static ScriptManagementExtension
{
        private const string ScriptFormat = "\t<script src=\"{0}\" type=\"text/javascript\"></script>";
        private const string CSSFormat = "\t<link href=\"{0}\"  rel=\"stylesheet\" type=\"text/css\"></link>";
        private static string IncludeHeader(HtmlHelper helper, string key, string path, string format)
        {
            var context = helper.ViewContext.HttpContext;
            var exists = context.Items.Contains(key);
            if (!exists)
            {
                var url = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
                context.Items[key] = true;
                return string.Format(format, url.Content(path));
            }
            return null;
        }
        public static string IncludeScript(this HtmlHelper helper, string path)
        {
            return IncludeScript(helper, path.ToLower(), path);
        }
        public static string IncludeScript(this HtmlHelper helper, string key, string path)
        {
            return IncludeHeader(helper, key, path, ScriptFormat);
        }
        public static string IncludeCSS(this HtmlHelper helper, string path)
        {
            return IncludeCSS(helper, path.ToLower(), path);
        }
        public static string IncludeCSS(this HtmlHelper helper, string key, string path)
        {
            return IncludeHeader(helper, key, path, CSSFormat);
        }
}
使用的時候在masterPage的head區域加入一個佔位標記:

<asp:ContentPlaceHolder ID="ScriptContent" runat="server" />
然後在每個view中你都可以通過下面的代碼來註冊腳本了:
<%= Html.IncludeCSS("http://www.cnblogs.com/Content/Site.css") %>
<%= Html.IncludeCSS("http://www.cnblogs.com/Content/ui.jqgrid.css")%>
<%= Html.IncludeCSS("jQuery_Theme", Html.GetThemePath()) %>
<%= Html.IncludeScript("http://www.cnblogs.com/Scripts/jquery-1.3.2.min.js")%>
...
當然,我也有我的困惑。我的困惑就是,爲什麼Microsoft沒有直接提供Script管理解決方案,抑或是已經提供了,我沒有發現?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章