也说 ASP.NET MVC的 Script 管理

本文介绍了一种在ASP.NET MVC中简化脚本和CSS文件管理的方法,通过使用自定义扩展方法来避免脚本冲突,并确保高效加载。该方案允许开发者在MasterPage头部注册脚本和样式表,同时避免重复加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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区。

思考半天,感觉复杂了一点。我的解决方案比较简单,每次注册脚本调用一个扩展足够了。

ExpandedBlockStart.gif 代码
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管理解决方案,抑或是已经提供了,我没有发现?

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值