在ASP.NET中替換Sys.Services的方法
使用自定義類替換Sys.Services.ProfileService對(duì)象
一般來(lái)說(shuō),這是最容易想到的辦法。我們可以寫(xiě)一個(gè)類替換Sys.Services._ProfileService 類(這個(gè)類完全通過(guò) prototype擴(kuò)展,因此對(duì)于繼承非常友好),甚至完全重寫(xiě)一個(gè)類,這個(gè)一般就看具體情況了。假設(shè)我們已經(jīng)定義了這么一個(gè)類 “Jeffz.Services.ProfileService”,并將其包含在MyProfile.Service.js中,就要開(kāi)始使用了。那么還要注意些什么呢?
需要注意的就是順序,我們一般會(huì)使用ScriptManager引入該JS,如下:
- <asp:ScriptManager ID="ScriptManager1" runat="server"
EnablePartialRendering="false">- <Scripts>
- <asp:ScriptReference Path="MyProfileService.js" />
- < SPAN>Scripts>
- <ProfileService LoadProperties="ZipCode, Address.City"
Path="MyProfile.asmx"/>- < SPAN>asp:ScriptManager>
我們?yōu)镻rofileService節(jié)點(diǎn)加上了LoadProperties屬性,表明需要預(yù)加載Profile中的ZipCode和Address這個(gè) Profile Group下的City屬性。另外,我們將EnablePartialRendering屬性設(shè)為了False,避免出現(xiàn)多余的代碼。
- <script src="/Value-Add-WebSite/WebResource.axd?d=...;t=..." type=
"text/javascript"></script>- <script type="text/javascript">
- </script>
- <script src="MyProfileService.js" type="text/javascript"></script>
***行引入的是 MicrosoftAjax.js,它之中定義了ASP.NET AJAX中默認(rèn)的ProfileService,而緊接著就是對(duì)于ProfileService的使用:設(shè)定其Path以及預(yù)加載的 Properties。在引入之后千萬(wàn)不能忘了要將這些信息進(jìn)行保留。但是這兩者之間無(wú)法插入任何代碼,因此我們可以在 MyProfileService.js里添加如下的代碼,以保留這些信息:
- var path = Sys.Services.ProfileService.get_path();
- if (!path)
- {
- path = Sys.Services._ProfileService.WebServicePath;
- }
- var properties = Sys.Services.ProfileService.properties;
- var newnewInstance = new Jeffz.Services.ProfileService();
- newInstance.set_path(path);
- newInstance.properties = properties;
- Sys.Services.ProfileService = newInstance;
當(dāng)然,可能代碼會(huì)根據(jù)實(shí)際情況略有不同,但是注意JavaScript引入以及執(zhí)行的順序,在做任何自定義工作時(shí)都是非常重要的。
有人也許會(huì)問(wèn),既然已經(jīng)重新定義了自己的實(shí)現(xiàn),為什么還要將其“偽裝”成默認(rèn)的ProfileService呢?因?yàn)檫@種“自定義”其實(shí)并不為“官方” 所承認(rèn),這么做能夠保證了兼容性,保證了第三方的組件也能使用Profile Service,即使它們沒(méi)有“意識(shí)”到?jīng)]有使用ASP.NET AJAX提供的默認(rèn)Profile Service。以上介紹在ASP.NET中替換Sys.Services的方法
【編輯推薦】