本文是 Asp.net Ajax 程式設計備忘錄----細數28個伺服器端控件 的續篇,繼續把Ajax Control Toolkit使用時的細節展示出來。首先我将28個控件簡單分了一下類:
下面一一道來:
1.Accordion
觀點: (1) $find('ctl00_ContentPlaceHolder1_MyAccordion_AccordionExtender')這裡找到的是BehaviorID!!
ctl00_ContentPlaceHolder1_MyAccordion是控件的ClientID後面拼上_AccordionExtender就是BehaviorID
(2)通過BehaviorID找到的Behavior是所有Behavior的引用,behavior.set_FadeTransitions()的方式實作具
體某一個Behavior的通路修改 實作參見該控件源代碼: AccordionBehavior.js
(3)其實這裡BehaviorID的設計很不好,既然BehaviorID是一個伺服器端控件的共性,為什麼不封裝抽象一下呢
< script language = " javascript " type = " text/javascript " >
function toggleFade()
{
var behavior = $find('ctl00_ContentPlaceHolder1_MyAccordion_AccordionExtender');
if (behavior)
{
behavior.set_FadeTransitions(!behavior.get_FadeTransitions());
}
}
function changeAutoSize()
{
var behavior = $find('ctl00_ContentPlaceHolder1_MyAccordion_AccordionExtender');
var ctrl = $get('autosize'); //這裡找的是下拉清單控件,不是Behavior
if (behavior)
{
var size = 'None'; // 這裡順便看看怎麼使用Select
switch (ctrl.selectedIndex)
{
case 0 :
behavior.get_element().style.height = 'auto';
size = AjaxControlToolkit.AutoSize.None;
break;
case 1 :
behavior.get_element().style.height = '400px';
size = AjaxControlToolkit.AutoSize.Fill;
break;
case 2 :
behavior.get_element().style.height = '400px';
size = AjaxControlToolkit.AutoSize.Limit;
break;
}
behavior.set_AutoSize(size);
}
if (document.focus)
{
document.focus();
}
}
</ script >
2. AlwaysVisibleControl
觀點: 這個控件比較簡單,但是控制顯示位置的代碼還是很有用的 看看:
< asp:DropDownList ID ="ddlPosition" runat ="server"
AutoPostBack ="true" OnSelectedIndexChanged ="OnChange" >
< asp:ListItem Text ="Default" Selected ="true" Value ="None" />
< asp:ListItem Text ="Top Left" Value ="TL" />
< asp:ListItem Text ="Top Center" Value ="TC" />
< asp:ListItem Text ="Top Right" Value ="TR" />
< asp:ListItem Text ="Middle Left" Value ="ML" />
< asp:ListItem Text ="Middle Center" Value ="MC" />
< asp:ListItem Text ="Middle Right" Value ="MR" />
< asp:ListItem Text ="Bottom Left" Value ="BL" />
< asp:ListItem Text ="Bottom Center" Value ="BC" />
< asp:ListItem Text ="Bottom Right" Value ="BR" />
</ asp:DropDownList >
/// < summary >
/// Update properties of the extender
/// </ summary >
protected void OnChange(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(ddlPosition.SelectedValue) || ddlPosition.SelectedValue.Length != 2)
{
avce.Enabled = false;
return;
}
avce.Enabled = true;
switch (ddlPosition.SelectedValue[0])
{
case 'T' :
avce.VerticalSide = VerticalSide.Top;
break;
case 'M' :
avce.VerticalSide = VerticalSide.Middle;
break;
case 'B' :
avce.VerticalSide = VerticalSide.Bottom;
break;
default:
avce.Enabled = false;
return;
}
switch (ddlPosition.SelectedValue[1])
{
case 'L':
avce.HorizontalSide = HorizontalSide.Left;
break;
case 'C':
avce.HorizontalSide = HorizontalSide.Center;
break;
case 'R':
avce.HorizontalSide = HorizontalSide.Right;
break;
default:
avce.Enabled = false;
return;
}
}
3.Animation
觀點:今天多說幾句
(1)Sys.UI.DomElement.getLocation(b) 取得控件位置的函數,常用!!!
(2)動畫分為兩種:Animation Action 後者的強大讓我很興奮
(3)<Sequence> </Sequence> 順序執行的動畫腳本
(4)<Parallel> <Parallel > 并發執行的動畫腳本
(5)【Action】 <StyleAction AnimationTarget="btnCloseParent" Attribute="opacity" value="0" />
控制目标元素外觀樣式,屬性--值的格式修改,一個元素可以應用多個StyleAction
(6)【Action】<EnableAction AnimationTarget="ctl00_ContentPlaceHolder1_btnInfo" Enabled="true" />
控件是否可用使用的方式跟上面是一樣的,目前控件可省略AnimationTarget
(7)【Action】 <ScriptAction Script="Cover($get('ctl00_ContentPlaceHolder1_btnInfo'), $get('flyout'));" />
執行一段腳本的Action
(8) 【Action】 <HideAction />隐藏目标的控件
(9) 【Action】<OpacityAction AnimationTarget="info" Opacity="0" /> 設定透明度的Action
(10)【Animation】 <FadeIn AnimationTarget="info" Duration=".2"/> <FadeOut /> 淡入淡出
(11)【Animation】<Scale ScaleFactor="0.05" Center="true" ScaleFont="true" FontUnit="px" />
控制目标元素的大小但是注意:If scaleFont is true, the size of the font will also scale with the element.
If center is true, then the element's center will not move as it is scaled. It is important to note that the
target must be positioned (i.e. absolutely) so that settings its top/left properties will change its location
in order for center to have an effect.
(12) 【Animation】 <Pulse Duration=".1" /> 脈搏跳動效果
(13) 【Animation】 <Color Duration=".2" StartValue="#FFFFFF" EndValue="#FF0000" Property="style" PropertyKey="color" />
顔色漸變效果,設定起始結束顔色就可以
(14) 【Animation】 <Resize Width="260" Height="280" />改變元素的大小Action
4.CascadingDropDown
觀點:上回還是忽略了一個細節Category!這個可以從兩方面來講:
(1)它是什麼:官方說法The name of the category this DropDownList represents
其實打開~/App_Data/CarsService.xml你就發現這是Xml的元素标簽
(2)從這個角度我們就解決了為什麼關聯,即關聯的本質;同時也明白了
調用Service的參數約定
5.CollapsiblePanel
觀點:(1)可以自動展開 自動收縮Autoexpand="true" AutoCollapse="true"但是這兩個本身是互斥的不能同時為True
同時也舊不要設定 Collapsed="True"了 沒有意義
(2) TextLabelID="Label1"這個屬性有什麼深意\進階的操作麼?我沒有發現
6.ConfirmButton
有一個細節:要擴充的LinkButton Button 以及ConfirmButtonExtender都要放在updatepanel裡面
如果是放在外面,點選“确定”或者“取消”之後還是會導緻頁面重新整理!
7.DragPanel
觀點:panel6包含panel7(标題) panel8(内容)擴充的對象是panel6
代碼示意
< asp:Panel ID ="Panel6" runat ="server" Width ="100%" >
< asp:Panel BorderStyle ="Solid" BorderWidth ="2px" BorderColor ="black" ID ="Panel7" runat ="server" Width ="100%" Height ="20px" >
< div class ="dragMe" > Drag Me </ div >
</ asp:Panel >
< asp:Panel BorderStyle ="Solid" BackColor ="#0B3D73" ForeColor ="whitesmoke" BorderWidth ="2px" BorderColor ="black" ID ="Panel8" runat ="server" Width ="100%" Height ="250px" Style ="overflow: scroll;" >
< div >
< p > This panel will reset its position on a postback or page refresh. </ p >
< hr />
< p > <% = GetContentFillerText() %> </ p >
</ div >
</ asp:Panel >
</ asp:Panel >
< ajaxToolkit:DragPanelExtender ID ="DragPanelExtender1" runat ="server" TargetControlID ="Panel6" DragHandleID ="Panel7" >
8.DropDown
觀點:在IE浏覽器中下拉清單總是在最前面的,嚴重影響頁面效果
細節: (1)示例中是對一個Label進行的擴充,我試着擴充TextBox效果更好!
官方的說法:DropDown is an ASP.NET AJAX extender that can be attached to almost any ASP.NET control.
(2)我們還有一個收獲就是下面的代碼,有不少小技巧
代碼示意:
< asp:UpdatePanel id ="Update" runat ="server" >
< ContentTemplate >
< asp:Label id ="lblSelection" runat ="server" Style ="padding: 5px;" />
</ ContentTemplate >
< Triggers >
< asp:AsyncPostBackTrigger ControlID ="Option1" EventName ="Click" />
< asp:AsyncPostBackTrigger ControlID ="Option2" EventName ="Click" />
< asp:AsyncPostBackTrigger ControlID ="Option3" EventName ="Click" />
</ Triggers >
</ asp:UpdatePanel >
< ajaxToolkit:UpdatePanelAnimationExtender ID ="UpdateAnimation" runat ="server" TargetControlID ="Update" BehaviorID ="Highlight" >
< Animations >
< OnUpdated >
< Sequence >
< ScriptAction Script ="$find('Highlight')._onUpdated._animation._animations[1].set_target($get('ctl00_ContentPlaceHolder1_lblSelection'));" />
<Color Duration=".5" StartValue="#FFFF90" EndValue="#FFFFFF" Property="style" PropertyKey="backgroundColor" />
</Sequence>
</OnUpdated>
</Animations>
</ajaxToolkit:UpdatePanelAnimationExtender>
9.DropShadow
觀點: 我們的美工說這個很簡單就可以實作
10.DynamicPopulate
觀點: (1)我們非常欣慰的一點就是BehaviorID="dp1"還記得開篇時的說法麼,終于出現了
(2)PopulateTriggerControlID 觸發器綁定的控件 單擊時觸發 容易忽略掉!
(3)CustomScript 怎麼用呢??This script must evaluate to a string value. ??
(4)這裡是與别處不同的,直接使用了Behavior,Behavior包含了兩要素:對誰擴充+ 擴充了什麼功能
代碼示意:
< asp:Panel ID ="Panel1" runat ="server" CssClass ="dynamicPopulate_Normal" >
</ asp:Panel > //要擴充的panel
< ajaxToolkit:DynamicPopulateExtender ID ="dp" BehaviorID ="dp1" runat ="server"
ClearContentsDuringUpdate ="true"
PopulateTriggerControlID ="Label1"
TargetControlID ="Panel1"
ServiceMethod ="GetHtml"
UpdatingCssClass ="dynamicPopulate_Updating" >
</ ajaxToolkit:DynamicPopulateExtender >
< script runat ="server" >
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetHtml(string contextKey)
{
// a little pause to mimic a latent call.
//
System.Threading.Thread.Sleep(250);
string value = "";
if (contextKey == "U")
{
value = DateTime.UtcNow.ToString();
} else
{
value = String.Format("{0:" + contextKey + "}", DateTime.Now);
}
return String.Format("<span style='font-family:courier new;font-weight:bold;'>{0}</span>", value);
}
</ script >
< asp:Content ID ="Content1" ContentPlaceHolderID ="ContentPlaceHolder1" Runat ="Server" >
< script type ="text/javascript" >
function updateDateKey(value)
{
var behavior = $find('dp1'); //這樣使用BehaviorID可是友善多了
if (behavior)
{
behavior.populate(value);// 内部實作調用了Service
}
}
Sys.Application.add_load(function()
{updateDateKey('G');}); //頁面加載時要執行的腳本!
</ script >
11.FilteredTextBox
觀點:我還是沒有解決可以輸入中文的問題,看實作的代碼中有一部分是排除對一些特殊鍵掃描碼
限制的代碼,是否是個切入點呢?解決中……
特殊鍵排除代碼:
< var scanCode;
if (evt.rawEvent.keyIdentifier) {
// Safari
// Note (Garbin): used the underlying rawEvent insted of the DomEvent instance.
if (evt.rawEvent.ctrlKey || evt.rawEvent.altKey || evt.rawEvent.metaKey) {
return;
}
if (evt.rawEvent.keyIdentifier.substring(0,2) ! = "U+" ) {
return;
}
scanCode = evt.rawEvent.charCode;
if (scanCode == 63272 ) {
return;
}
}
else {
scanCode = evt.charCode;
}
if (scanCode && scanCode > = 0x20 ) {
var c = String.fromCharCode(scanCode);
if(!this._processKey(c)) {
evt.preventDefault();
}
}
}
12.HoverMenu
觀點: HttpUtility.HtmlEncode()使用 HttpUtility.HtmlEncode 将危險的符号轉換為它們的 HTML 表示形式。
代碼示意:
<asp:Label Font-Bold="true" ID="Label1" runat="server" Text='<%# HttpUtility.HtmlEncode(Convert.ToString(Eval("Title"))) %>'></asp:Label></td>
<asp:Label ID="Label2" runat="server" Text='<%# HttpUtility.HtmlEncode(Convert.ToString(Eval("Description"))) %>'></asp:Label></td>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Priority") %>'></asp:Label>
13.ModalPopup
觀點:Opera浏覽器中不正常,隻有一部分區域是灰掉的
14.MutuallyExlcusiveCheckBox
觀點:寫了一個Checkbox關聯的JS如下
< input type = " checkbox " name = " checkA " onpropertychange = " for(i=0;i<A.children.length;i++){A.children[i].checked=this.checked} " > a
< br >
< span id = " A " >
< input type = " checkbox " name = " A1 " >
< input type = " checkbox " name = " A2 " >
< input type = " checkbox " name = " A3 " >
</ span >
15.NoBot
觀點: 簡單解釋什麼意思,你點選一個按鈕需要一秒鐘的時間,而這一秒鐘的時間你不可能再做其他的操作
比如再點一次;這樣舊區分出了人和機器。避免機器人自動點選 注冊 暴力破解之類的事情
16.NumericUpDown
觀點:上下按鈕是可以自定義美化的,不需要美化 TargetButtonDownID=" " TargetButtonUpID=" "
代碼示意:
< asp:Image ID = " img1 " runat = " server " ImageUrl = " ~/images/down.gif " AlternateText = " Down " Width = " 20 " Height = " 15 " />
< asp:Image ID = " img2 " runat = " server " ImageUrl = " ~/images/up.gif " AlternateText = " Up " Width = " 20 " Height = " 15 " />
< ajaxToolkit:NumericUpDownExtender ID = " NumericUpDownExtender4 " runat = " server "
TargetControlID = " TextBox4 " Width = " 80 " TargetButtonDownID = " img1 "
TargetButtonUpID = " img2 " RefValues = "" ServiceDownMethod = "" ServiceUpMethod = "" />
17.PagingBulletedList
觀點: 我用這個做了一個管理超連結的頁面,效果不錯
代碼示意:
< ajaxToolkit:PagingBulletedListExtender ID ="PagingBulletedListExtender1" BehaviorID ="PagingBulletedListBehavior1" runat ="server"
TargetControlID ="BulletedList1"
ClientSort ="true"
IndexSize ="1"
Separator =" - "
SelectIndexCssClass ="selectIndex"
UnselectIndexCssClass ="unselectIndex" />
18.PasswordStrength
觀點:示例中Textbox1 Textbox3都沒有添加TextMode="Password" 是以在界面上我們可以輸入中文;
而且輸入中文很快就達到較高安全度,當然這沒有什麼用處
19.PopupControl
觀點:任何控件上都可以彈出任何内容,我認為跟HoverMenu在使用者體驗上沒有太大的差別
20.Rating
觀點:使用的時候體驗很糟糕,問題在哪裡呢?滑鼠跟随!滑鼠移動等級也會變,而你真正要修改還要點選一下
21.ReorderList
觀點:這個控件是非常獨立,并且還是适用于表現Buleted的資料,二維資料就無能為例了
DataSourceID="ObjectDataSource1" 這是必須要有的!下面是它的Template架構:
< ajaxToolkit:ReorderList ID ="ReorderList1" PostBackOnReorder ="false" runat ="server" DataSourceID ="ObjectDataSource1" CallbackCssStyle ="callbackStyle"
DragHandleAlignment ="Left" ItemInsertLocation ="Beginning" DataKeyField ="ItemID" SortOrderField ="Priority" >
< ItemTemplate ></ ItemTemplate >
< EditItemTemplate ></ EditItemTemplate >
< ReorderTemplate ></ ReorderTemplate >
< DragHandleTemplate > </ DragHandleTemplate >
< InsertItemTemplate > </ InsertItemTemplate >
</ ajaxToolkit:ReorderList >
22.ResizableControl
觀點:看看飛鴿 I桌面這種應用實踐,還真是沒有見到用它的,用在什麼地方呢?
看來網際網路要的就是創意!沒有做不到隻有想不到!
23.RoundedCorners
觀點:我們的美工告訴我這些是很簡單的事情;園子裡也在争論頁面美化由誰來做的話題,其實有必要劃這麼清除麼?
比如我是開發人員我要做一個淡入淡出效果,我需要的參數完全可以讓美工提供。我們還要翻顔色對照表,汗!
而美工使用Ajax也是有難度,關鍵原則:成本最小化!
24.Slider
觀點:新浪論壇用來分頁了,呵呵,還有的用來調“時間----------|----熱度”,真是創意!
25.TextBoxWatermark
觀點:這是應用很廣泛的一個,遠遠超出我的想象,這個提示效果很直接,不錯;
26.UpdatePanelAnimation
觀點:應用還是時間較短的場合,時間長了這個動畫就有點不合适了,畢竟這是一個完整的動作;時間長還是UpdateProgress比較好
27.ToggleButton
觀點:這裡突破的是一個慣性:勾選CheckBox頁面不會有太大的變化!而封裝成按鈕更符合人們的使用習慣;示例設計的不好
沒展現這一點
28.ValidatorCallout
觀點:Errormessage是一個開放的屬性,我們可以進行豐富的擴充,大膽的想象,讓顯示出來的氣泡更有意義
代碼示意:
< asp:RequiredFieldValidator runat ="server" ID ="PNReq" ControlToValidate ="PhoneNumberTextBox" Display ="None" ErrorMessage ="<b>
Required Field Missing</b><br />A phone number is required.<div style='margin-top:5px;padding:5px;border:1px solid #e9e9e9;background-color:white;'>
<b>Other Options:</b><br /><a href='javascript:alert("No phone number available in profile.");'>Extract from Profile</a></div>" />
< ajaxToolkit:ValidatorCalloutExtender runat ="Server" ID ="PNReqE" TargetControlID ="PNReq" HighlightCssClass ="highlight" Width ="350px" />