整合jQuery UI 與ASP. NET Web Form - 1

by vivid 18. 六月 2014 02:31

.NET Magazine國際中文電子雜誌
者:許薰尹
稿:張智凱
文章編號:N140614902
出刊日期:2014/6/18
開發工具:Visual Studio 2013 Ultimate Update 2
版本:.NET Framework 4.5.5x

ASP.NET Web Forms使用Web伺服器控制項(Web Server Control)來建立使用者介面,以讓使用者透過文字方塊、按鈕…等等UI項目來讓使用者輸入資料。這些Web伺服器控制項在伺服端執行時,會有一個生成標籤的程序(稱Rendering),藉以產生HTML標籤,讓瀏覽器顯示適當的UI畫面>例如,若有一個ASP.NET Web Form Button伺服器控制定義如下:

<asp:Button ID = "Button1" runat = "server" Text = "Button" />

在執行時期便會產生以下的HTML Input(type="submit")標籤:

<input type = "submit" name = "Button1" value = "Button" id = "Button1">

又如,若有一個ASP.NET Web Form TextBox伺服器控制定義如下:

<asp:TextBox ID = "TextBox1" runat = "server"> </asp:TextBox>

在執行時期便會產生以下的HTML Input(type="text")標籤:

<input name = "TextBox1" type = "text" id = "TextBox1">

而jQuery UI則是在用戶端(瀏覽器)進行套用的,因此若要讓ASP.NET Web伺服器控制項能和jQuery UI整合在一起,首要的工作便是要知道你所使用的ASP.NET Web伺服器控制項,在執行階段產生的HTML標籤是否適合搭配jQuery UI來使用。例如,以下為TreeView控制項的範例:

<asp:TreeView ID = "TreeView1" runat = "server">
    <Nodes>
        <asp:TreeNode Text = "File" Value = "File">
            <asp:TreeNode Text = "Open" Value = "Open"> </asp:TreeNode>
            <asp:TreeNode Text = "Close" Value = "Close"> </asp:TreeNode>
        </asp:TreeNode>
        <asp:TreeNode Text = "Edit" Value = "Edit">
            <asp:TreeNode Text = "Copy" Value = "Copy"> </asp:TreeNode>
            <asp:TreeNode Text = "Paste" Value = "Paste"> </asp:TreeNode>
        </asp:TreeNode>
    </Nodes>
</asp:TreeView>

 

它將生成以下非常複雜的HTML標籤,以及一些JavaScript程式碼,這些程式碼很容易和jQuery UI的程式發生衝突,因此比較難以進行整合:

<a href="#TreeView1_SkipLink" style="position:absolute;left:-10000px;top:auto;width:1px;height:1px;overflow:hidden;">Skip Navigation Links.</a><div id="TreeView1">
    <table cellpadding="0" cellspacing="0" style="border-width:0;">
        <tr>
            <td><a id="TreeView1n0" href="javascript:TreeView_ToggleNode(TreeView1_Data,0,document.getElementById(&#39;TreeView1n0&#39;),&#39; &#39;,document.getElementById(&#39;TreeView1n0Nodes&#39;))"><img src="/WebResource.axd?d=-n2KnhPEOy8tY2UhU96Dm_QmaxBaFqshCDAZcWA9-Zof0lH_v_D42YlugVjQakfkmwYNVGpEyBo9xkq4nA7yhhq4YQOk1_fp81VQXFa5yKM1&amp;t=635117217316159565" alt="Collapse File" style="border-width:0;" /></a></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sFile&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t0&#39;);" id="TreeView1t0">File</a></td>
        </tr>
    </table><div id="TreeView1n0Nodes" style="display:block;">
        <table cellpadding="0" cellspacing="0" style="border-width:0;">
            <tr>
                <td><div style="width:20px;height:1px"></div></td><td><img src="/WebResource.axd?d=Vnw6Nul5Gi8dLBSg8ZsULSvBGUbhIOuTEiGcqHJJXd6lb2wEi0CVQiH8PXAR4AeFJRS4ISCcSaEti2RXEkMPGgOU6ON6KKNE9Cos-k_B_ds1&amp;t=635117217316159565" alt="" /></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sFile\\Open&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t1&#39;);" id="TreeView1t1">Open</a></td>
            </tr>
        </table><table cellpadding="0" cellspacing="0" style="border-width:0;">
            <tr>
                <td><div style="width:20px;height:1px"></div></td><td><img src="/WebResource.axd?d=Vnw6Nul5Gi8dLBSg8ZsULSvBGUbhIOuTEiGcqHJJXd6lb2wEi0CVQiH8PXAR4AeFJRS4ISCcSaEti2RXEkMPGgOU6ON6KKNE9Cos-k_B_ds1&amp;t=635117217316159565" alt="" /></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sFile\\Close&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t2&#39;);" id="TreeView1t2">Close</a></td>
            </tr>
        </table>
    </div><table cellpadding="0" cellspacing="0" style="border-width:0;">
        <tr>
            <td><a id="TreeView1n3" href="javascript:TreeView_ToggleNode(TreeView1_Data,3,document.getElementById(&#39;TreeView1n3&#39;),&#39; &#39;,document.getElementById(&#39;TreeView1n3Nodes&#39;))"><img src="/WebResource.axd?d=-n2KnhPEOy8tY2UhU96Dm_QmaxBaFqshCDAZcWA9-Zof0lH_v_D42YlugVjQakfkmwYNVGpEyBo9xkq4nA7yhhq4YQOk1_fp81VQXFa5yKM1&amp;t=635117217316159565" alt="Collapse Edit" style="border-width:0;" /></a></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sEdit&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t3&#39;);" id="TreeView1t3">Edit</a></td>
        </tr>
    </table><div id="TreeView1n3Nodes" style="display:block;">
        <table cellpadding="0" cellspacing="0" style="border-width:0;">
            <tr>
                <td><div style="width:20px;height:1px"></div></td><td><img src="/WebResource.axd?d=Vnw6Nul5Gi8dLBSg8ZsULSvBGUbhIOuTEiGcqHJJXd6lb2wEi0CVQiH8PXAR4AeFJRS4ISCcSaEti2RXEkMPGgOU6ON6KKNE9Cos-k_B_ds1&amp;t=635117217316159565" alt="" /></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sEdit\\Copy&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t4&#39;);" id="TreeView1t4">Copy</a></td>
            </tr>
        </table><table cellpadding="0" cellspacing="0" style="border-width:0;">
            <tr>
                <td><div style="width:20px;height:1px"></div></td><td><img src="/WebResource.axd?d=Vnw6Nul5Gi8dLBSg8ZsULSvBGUbhIOuTEiGcqHJJXd6lb2wEi0CVQiH8PXAR4AeFJRS4ISCcSaEti2RXEkMPGgOU6ON6KKNE9Cos-k_B_ds1&amp;t=635117217316159565" alt="" /></td><td style="white-space:nowrap;"><a class="TreeView1_0" href="javascript:__doPostBack(&#39;TreeView1&#39;,&#39;sEdit\\Paste&#39;)" onclick="TreeView_SelectNode(TreeView1_Data, this,&#39;TreeView1t5&#39;);" id="TreeView1t5">Paste</a></td>
            </tr>
        </table>
    </div>
</div><a id="TreeView1_SkipLink"></a>

 

在這一篇文章中,將要探討幾個適合和jQuery UI Widget整合的ASP.NET Web伺服器控制項。

 

Button伺服器控制項

我們先從Button伺服器控制項來談起,參考以下ASP.NET Web Form網頁中包含一個Button伺服器控制項,註冊了伺服端的Click事件。要整合jQuery UI的Button Widget,只需要在Web Form之中引用jQuery UI樣式,jQuery、jQuery UI程式庫然後在jQuery 的ready事件中叫用jQuery UI Button Widget的.button()方法初始化即可:

<%@ Page Language = "C#" %>

<!DOCTYPE html>
<script runat = "server">
    protected void Button1_Click( object sender , EventArgs e ) {
        Label1.Text = "You Click Button 1";
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:Button ID = "Button1" runat = "server" Text = "Click" OnClick = "Button1_Click" />
            <asp:Label ID = "Label1" runat = "server" Text = ""></asp:Label>
        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#Button1").button();
        });
    </script>
</body>
</html>

 

這個範例的執行結果如下圖所示,Button套用了jQuey UI的樣式,當使用者使用滑鼠點選按鈕,也會正確地觸發伺服端的Click事件:

clip_image002

圖 1:Button範例。

使用自訂按鈕圖示

jQuery UI的Button Widget有一個icons選項,可以用來設定按鈕上要顯示的小圖示,jQuery UI內建許多圖示,圖示列表可參考:http://api.jqueryui.com/theming/icons/。讓我們為上例的按鈕加入圖示,參考下列程式碼,利用primary設定圖示要顯示在按鈕文字的左方:

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">

    protected void Button1_Click( object sender , EventArgs e ) {
        Label1.Text = "You Click Button 1";
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:Button ID = "Button1" runat  ="server" Text = "Click" OnClick = "Button1_Click" />
            <asp:Label ID = "Label1" runat = "server" Text = ""></asp:Label>
        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            //圖示不會出現
            $("#Button1").button({
                icons: { primary: "ui-icon-circle-plus" }
            });
        });
    </script>
</body>
</html>

不過當你執行這個網頁,按鈕的圖示卻不會出現,參考以下執行結果:

clip_image004

圖 2:Button範例-按鈕的圖示不會出現。

為什麼會有這個奇怪的現象呢?我們來檢視一下套用jQuery UI之後,Button伺服器產生的標籤將會變成input欄位:

<input type="submit" name="Button1" value="Click" id="Button1" class="ui-button ui-widget ui-state-default ui-corner-all" role="button" aria-disabled="false">

在jQuery UI中使用input(type="submit")欄位的按鈕只能夠顯示純文字,不能夠顯示圖示,因此若要能夠顯示自訂圖示,需要改用<button>標籤來定義按鈕,因此你需要自行加工處理這個問題。

修訂自訂圖示顯示

修改上個範例如下,我們需要將ASP.NET Button伺服器控制項產生的Input標籤做修改,換成<button>標籤這樣才能夠和jQuery UI Button Widget整合 :

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">

    protected void Button1_Click( object sender , EventArgs e ) {
        Label1.Text = "You Click Button 1";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Content/themes/sunny/jquery-ui.css" rel="stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="Button1" runat="server" Text="Click" OnClick="Button1_Click" />
            <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        </div>
    </form>
    <script src="Scripts/jquery-2.0.3.min.js"> </script>
    <script src="Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#Button1").button().hide();
            var b = $("<button>").button({
                icons:
                {
                    primary: 'ui-icon-circle-plus'
                },
                label: $("#Button1").val()
            });

            b.insertBefore($("#Button1"));

            b.click(function (event) {
                event.preventDefault();
                $(this).next().click();
            });
           
        });
    </script>
</body>
</html>

 

首先在jQuery Ready事件之中,先叫用hide()方法將input( type="submit)按鈕隱藏起來。利用jQuery動態建立一個<button>標籤,並設定使用ui-icon-circle-plus圖示,使用label選項設定<button>標籤上顯示的文字就是input( type="submit)按鈕上的文字。接著叫用insertBefore方法,將<button>插入原來的input( type="submit)按鈕前方,最後註冊<button>的Click事件,在事件發生時,叫用event.preventDefault()方法擋掉預設的事件行為,然後觸發被隱藏的input( type="submit)按鈕之Click事件。

這個範例的執行結果請參考下圖所示:

clip_image006

圖 3:Button範例-顯示自訂圖示。

Hyperlink伺服器控制項

ASP.NET Hyperlink伺服器控制項產生的HTML標籤可以很容易地和jQuery UI Button Widget整合,例如以下Hyperlink伺服器控制項:

<asp:HyperLink ID = "HyperLink1" runat = "server" NavigateUrl = "~/01_button.aspx"> HyperLink </asp:HyperLink>

將產生以下的HTML標籤:

<a id = "HyperLink1" href = "01_button.aspx"> HyperLink </a>

因此我們只需要在Web Form中,於jQuery Ready事件叫用jQuery Button Widget的.button()方法進行初始化就可以了,參考以下範例:

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat = "server">

</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:HyperLink ID = "HyperLink1" runat = "server" NavigateUrl = "~/01_button.aspx"> HyperLink </asp:HyperLink>
        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#HyperLink1").button({
                icons: { primary: "ui-icon-key" }
            });
        });
    </script>
</body>
</html>

 

這個範例執行結果如下圖所示:

clip_image008

圖 4:Hyperlink伺服器控制項。

LinkButton伺服器控制項

LinkButton伺服器控制項會產生連結,例如以下範例:

<asp:LinkButton ID = "LinkButton1" runat = "server" OnClick = "LinkButton1_Click"> LinkButton </asp:LinkButton>

將會產生以下的<a>標籤,並在標籤中注入JavaScript程式碼,在連結被點選時,做POSTBACK動作,將資料送到伺服端:

<a id = "LinkButton1" href = "javascript:__doPostBack('LinkButton1','')"> LinkButton </a>

還好這些程式碼與jQuery UI Button Widget不衝突,直接整合便行了,參考以下整合範例:

 

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">

    protected void LinkButton1_Click( object sender , EventArgs e ) {
        Response.Write( "You click me");
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
      <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
    <div>
        <asp:LinkButton ID = "LinkButton1" runat = "server" OnClick = "LinkButton1_Click"> LinkButton </asp:LinkButton>
    </div>
    </form>
     <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#LinkButton1").button({
                icons: { primary: "ui-icon-key" }
            });
        });
    </script>
</body>
</html>

這個範例的執行結果請參考下圖所示,在按下按鈕時,伺服端的事件也能正常地執行:

clip_image010

圖 5:LinkButton伺服器控制項。

CheckBox伺服器控制項

CheckBox伺服器控制項可以和jQuery UI Button Widget正確地整合,以下程式碼註冊CheckBox伺服器伺服端的CheckedChanged事件,在CheckBox狀態變動時,自動在Label控制項上顯示Checked屬性的值。我們只需要在Web Form中,於jQuery Ready事件叫用jQuery Button Widget的.button()方法進行初始化就可以了,參考以下範例:

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">

    protected void CheckBox1_CheckedChanged( object sender , EventArgs e ) {
        Label1.Text = CheckBox1.Checked.ToString();
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
   
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:CheckBox ID = "CheckBox1" runat = "server" Text = "Is Member?" AutoPostBack = "True" OnCheckedChanged = "CheckBox1_CheckedChanged" />
                        <asp:Label ID = "Label1" runat = "server" Text = ""> </asp:Label>
        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#CheckBox1").button({
                icons: { primary: "ui-icon-key" }
            });
        });
    </script>
</body>
</html>

 

這個範例的執行結果請參考下圖所示,當你勾選CheckBox,便印出「true」:

clip_image012

圖 6:CheckBox伺服器控制項。

若取消勾選CheckBox,便印出「False」,請參考下圖所示:

clip_image014

圖 7:CheckBox伺服器控制項。

CheckBoxList伺服器控制項

CheckBoxList伺服器控制項是清單類型的控制項,一次呈現多個核取方塊,例如若有一個CheckBoxList伺服器控制項如下,預設RepeatDirection設定為「Table」:

<asp:CheckBoxList ID = "CheckBoxList1" runat = "server"
    OnSelectedIndexChanged = "CheckBoxList1_SelectedIndexChanged"
    AutoPostBack = "True"
    RepeatLayout = "Table"
    RepeatDirection = "Horizontal">
    <asp:ListItem Value = "111"> Mary </asp:ListItem>
    <asp:ListItem Value = "222"> Candy </asp:ListItem>
    <asp:ListItem Value = "333"> Lilly </asp:ListItem>
</asp:CheckBoxList>

 

執行時將產生以下UI介面:

clip_image016

圖 8:CheckBoxList伺服器控制項。

它產生的標籤如下,為多組Input與label標籤的組合,以<table>、<tr>、<td>標籤定位:

<table id="CheckBoxList1">
    <tbody>
        <tr>
            <td>
                <input id = "CheckBoxList1_0"
                    type = "checkbox" name = "CheckBoxList1$0"
                    onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$0\',\'\')', 0)"
                    value = "111">
                <label for = "CheckBoxList1_0">
                    Mary

                </label>

            </td>
            <td>
                <input id = "CheckBoxList1_1"
                    type = "checkbox"
                    name = "CheckBoxList1$1"
                    onclick = "    javascript: setTimeout('__doPostBack(\'CheckBoxList1$1\',\'\')', 0)"
                    value = "222">
                <label for = "CheckBoxList1_1">
                    Candy

                </label>
            </td>
            <td>
                <input id = "CheckBoxList1_2"
                    type = "checkbox"
                    name = "CheckBoxList1$2"
                    onclick = "    javascript: setTimeout('__doPostBack(\'CheckBoxList1$2\',\'\')', 0)"
                    value = "333">
                <label for = "CheckBoxList1_2">
                    Lilly

                </label>

            </td>
        </tr>
    </tbody>
</table>

 

<table>、<tr>、<td>標籤也可以與jQuery UI ButtonSet整合。參考以下範例程式碼,範例中註冊CheckBoxList1控制項的SelectedIndexChanged事件,在選到的項目變動時,將選到的項目顯示在Label:上:

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">
 
    protected void CheckBoxList1_SelectedIndexChanged( object sender , EventArgs e ) {
        Label1.Text = "";
        foreach ( ListItem item in CheckBoxList1.Items ) {
            if ( item.Selected )
                Label1.Text += item.Value + ",";
        }
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
</head>
<body>
    <form id= "form1" runat = "server">
        <div>
            <asp:CheckBoxList ID = "CheckBoxList1" runat = "server"
                OnSelectedIndexChanged = "CheckBoxList1_SelectedIndexChanged"
                AutoPostBack = "True"
                RepeatLayout = "Table"
                RepeatDirection = "Horizontal">
                <asp:ListItem Value = "111"> Mary </asp:ListItem>
                <asp:ListItem Value = "222"> Candy </asp:ListItem>
                <asp:ListItem Value = "333"> Lilly </asp:ListItem>
            </asp:CheckBoxList>

            <br />
            <asp:Label ID = "Label1" runat = "server" Text = ""> </asp:Label>

        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#CheckBoxList1").buttonset();

        });
    </script>
</body>
</html>

 

這個範例的執行結果請參考下圖所示:

clip_image018

圖 9:CheckBoxList伺服器控制項。

RepeatLayout屬性

CheckBoxList伺服器控制項有一個RepeatLayout屬性,可以用來變更它產生出來的標籤,例如若有一個CheckBoxList伺服器控制項如下,RepeatLayout屬性設定為「flow」

<asp:CheckBoxList ID = "CheckBoxList1" runat = "server" RepeatLayout = "Flow" OnSelectedIndexChanged = "CheckBoxList1_SelectedIndexChanged" AutoPostBack = "True" RepeatDirection = "Horizontal">
    <asp:ListItem Value = "111"> Mary </asp:ListItem>
    <asp:ListItem Value = "222"> Candy </asp:ListItem>
    <asp:ListItem Value = "333"> Lilly </asp:ListItem>
</asp:CheckBoxList>

它產生的標籤如下,為多組Input與label標籤的組合,使用<span>標籤代表CheckBoxList控制項的外觀:

<span id = "CheckBoxList1">
     <input id = "CheckBoxList1_0" type = "checkbox" name = "CheckBoxList1$0"
         onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$0\',\'\')', 0)"
         value = "111">
     <label for = "CheckBoxList1_0"> Mary </label>
     <input id = "CheckBoxList1_1" type = "checkbox" name = "CheckBoxList1$1"
         onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$1\',\'\')', 0)"
         value = "222">
     <label for = "CheckBoxList1_1"> Candy </label>
     <input id = "CheckBoxList1_2" type = "checkbox" name = "CheckBoxList1$2"
         onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$2\',\'\')', 0)"
         value = "333">
     <label for = "CheckBoxList1_2"> Lilly </label>
</span>

 

看起來和jQuery UI buttonset所需的標籤大致相同,可以很容易整合,參考以下範例程式碼範例,在網頁載入Page_Load事件觸發時,利用程式碼初始化CheckBoxList控制項,新增三個ListItem,然後利用資料繫結技術將資料顯示在CheckBoxList控制項上,並註冊SelectedIndexChanged事件,在選到的項目變動時,將選到的項目顯示在Label控制項上:

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">
 
    protected void Page_Load( object sender , EventArgs e ) {
        if ( !Page.IsPostBack ) {
            CheckBoxList1.Items.AddRange(
             new ListItem[ ] { new ListItem("Mary","111"),
                new ListItem("Candy","222"),
                new ListItem("Lilly","333")
            } );
            CheckBoxList1.DataBind( );
        }
    }
    protected void CheckBoxList1_SelectedIndexChanged( object sender , EventArgs e ) {
        Label1.Text = "";
        foreach ( ListItem item in CheckBoxList1.Items ) {
            if ( item.Selected )
                Label1.Text += item.Value + ",";
        }
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:CheckBoxList ID = "CheckBoxList1" runat = "server" RepeatLayout = "Flow" OnSelectedIndexChanged = "CheckBoxList1_SelectedIndexChanged" AutoPostBack = "True" RepeatDirection = "Horizontal"> </asp:CheckBoxList>
            <br />
            <asp:Label ID = "Label1" runat = "server" Text = "">< /asp:Label>
        </div>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>
        $(function () {
            $("#CheckBoxList1").buttonset();

        });
    </script>
</body>
</html>

 

最後只需要在jQuery Ready事件叫用jQuery Button Widget的. buttonset ()方法進行初始化,這個範例的執行結果請參考下圖所示:

clip_image020

圖 10:CheckBoxList伺服器控制項。

垂直顯示

CheckBoxList控制項的RepeatLayout屬性可以設定為「UnorderedList」,此時會強制將CheckBoxList控制項的RepeatDirection屬性設定為「Vertical」,如此CheckBoxList控制項便會產生<ul><li>標籤,以垂直的方式來顯示資料,例如以下範例程式碼:

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">
    protected void Page_Load( object sender , EventArgs e ) {
        if ( !Page.IsPostBack ) {
            CheckBoxList1.Items.AddRange(
                new ListItem[ ] { new ListItem("Mary","111"),
                new ListItem("Candy","222"),
                new ListItem("Lilly","333")
            } );
            CheckBoxList1.DataBind( );
        }
    }

    protected void CheckBoxList1_SelectedIndexChanged( object sender , EventArgs e ) {
        Label1.Text = "";
        foreach ( ListItem item in CheckBoxList1.Items ) {
            if ( item.Selected )
                Label1.Text += item.Value + ",";
        }
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
        ul {
            list-style-type: none;
        }
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div>
            <asp:Label ID = "Label1" runat = "server" Text = "Label"></asp:Label>
            <asp:CheckBoxList ID = "CheckBoxList1" runat = "server"
                RepeatLayout = "UnorderedList" OnSelectedIndexChanged = "CheckBoxList1_SelectedIndexChanged"
                AutoPostBack = "True" Width = "200px"> </asp:CheckBoxList>
        </div>

    </form>

    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
</body>
</html>

 

這個範例的執結果如下:

clip_image022

圖 11:CheckBoxList伺服器控制項。

CheckBoxList伺服器控制項產生的標籤如下:

<ul id = "CheckBoxList1" style = "width: 200px;">
    <li>
        <input id = "CheckBoxList1_0"
            type = "checkbox"
            name = "CheckBoxList1$0"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$0\',\'\')', 0)"
            value = "111">
        <label for = "CheckBoxList1_0">
            Mary

        </label>
    </li>
    <li>
        <input id = "CheckBoxList1_1"
            type = "checkbox"
            name = "CheckBoxList1$1"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$1\',\'\')', 0)"
            value = "222">
        <label for = "CheckBoxList1_1">
            Candy
        </label>

    </li>
    <li>
        <input id = "CheckBoxList1_2"
            type = "checkbox"
            name = "CheckBoxList1$2"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$2\',\'\')', 0)"
            value = "333">
        <label for = "CheckBoxList1_2">
            Lilly
        </label>
    </li>
</ul>

 

我們套用jQuery UI buttonset試試,在上個範例中加入以下程式碼:

<script>
    $(function () {
        var cbl = $("#CheckBoxList1");
        cbl.buttonset();

    });
</script>

這個範例的執行結果請參考下圖所示,雖然資料垂直顯示,但第一個與最後一個項目套用讓它以圓角呈現的樣式卻不如預期,此外寬度也不一致。預設jQuery UI的buttonset只支援水平方式呈現其中的項目,若想要改用垂直方式做顯示,則需要手動加入一些程式碼。

clip_image024

圖 12:CheckBoxList伺服器控制項。

我們可以修上個範例的程式碼,套用適當的樣式來解決此問題,觀察目前jQuery UI套用在<li>內<label>項目的樣式,第一個<li><label>項目套用「ui-corner-left」使左邊產生圓角效果;最後一個<li><label>項目套用「ui-corner-right」使右邊產生圓角效果。而<span>中文字的寬度會影響它的寬度:

<ul id = "CheckBoxList1" style = "width: 200px;" class = "ui-buttonset">
    <li>
        <input id = "CheckBoxList1_0"
            type = "checkbox"
            name = "CheckBoxList1$0"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$0\',\'\')', 0)"
            value = "111"
            class = "ui-helper-hidden-accessible">
        <label for = "CheckBoxList1_0"
            class = "ui-button ui-widget ui-state-default ui-button-text-only ui-corner-left"
            role = "button"
            aria-disabled = "false">
            <span class = "ui-button-text">
                Mary
            </span>
        </label>
    </li>
    <li>
        <input id = "CheckBoxList1_1"
            type = "checkbox"
            name = "CheckBoxList1$1"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$1\',\'\')', 0)"
            value = "222"
            class = "ui-helper-hidden-accessible">
        <label for = "CheckBoxList1_1"
            class = "ui-button ui-widget ui-state-default ui-button-text-only"
            role = "button"
            aria-disabled = "false">
            <span class = "ui-button-text">
                Candy
            </span>
        </label>
    </li>
    <li>
        <input id = "CheckBoxList1_2"
            type = "checkbox"
            name = "CheckBoxList1$2"
            onclick = "javascript: setTimeout('__doPostBack(\'CheckBoxList1$2\',\'\')', 0)"
            value = "333" class = "ui-helper-hidden-accessible">
        <label for = "CheckBoxList1_2"
            Class = "ui-button ui-widget ui-state-default ui-button-text-only ui-corner-right"
            role = "button"
            aria-disabled = "false">
            <span class = "ui-button-text">
                Lilly
            </span>
        </label>
    </li>
</ul>

 

因此,我們可以改寫jQuery Ready事件程式碼如下,移除第一個、最後一個項目的「ui-corner-left」與「ui-corner-right」樣式,為它們分別套用「ui-corner-top」與「ui-corner-bottom」項目。接著計算出<li>中最長的span的寬度,再利用迴圈將所有<span>的長度設定為最長的文字寬度:

<script>
    $(function () {
        var cbl = $("#CheckBoxList1");
        cbl.buttonset();

        $('li label:first', cbl).removeClass('ui-corner-left').addClass('ui-corner-top');
        $('li label:last', cbl).removeClass('ui-corner-right').addClass('ui-corner-bottom');
        textWidth = 0;
        $('span.ui-button-text', cbl).each(function (idx) {
            var w = $(this).width();
            if (w > textWidth) {
                textWidth = w
            };
        })
        $('span.ui-button-text', cbl).each(function (idx) {
            $(this).width(textWidth);
        })
    });
</script>

 

這個範例的執行結果請參考下圖所示:

clip_image026

圖 13:CheckBoxList伺服器控制項。

RadioButton伺服器控制項

RadioButton伺服器控制項用於資料的單選,它會產生Input(type=radio)標籤,例如以下伺服器控制項:

<asp:RadioButton ID = "RadioButton1" runat = "server" Text = "Male" GroupName = "gender" OnCheckedChanged = "RadioButton1_CheckedChanged" AutoPostBack = "True" />

產生的標籤看起來如下:

<input id = "RadioButton1" type = "radio" name = "gender" value = "RadioButton1"

<label for = "RadioButton1"> Male </label>

多個RadioButton伺服器控制項可以很容易和jQuery ButtonSet整合在一起,參考以下範例程式碼:

 

<%@ Page Language = "C#" %>

<!DOCTYPE html>

<script runat = "server">
    protected void RadioButton1_CheckedChanged( object sender , EventArgs e ) {
        if ( RadioButton1.Checked ) {
            Label1.Text = "Male";
        }
    }

    protected void RadioButton2_CheckedChanged( object sender , EventArgs e ) {
        if ( RadioButton2.Checked ) {
            Label1.Text = "Female";
        }
    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title> </title>
    <link href = "Content/themes/sunny/jquery-ui.css" rel = "stylesheet" />
    <style>
     
    </style>
</head>
<body>
    <form id = "form1" runat = "server">
        <div id = "mybuttonset">
            <asp:RadioButton ID = "RadioButton1" runat = "server" Text = "Male" GroupName = "gender" OnCheckedChanged = "RadioButton1_CheckedChanged" AutoPostBack = "True" />
            <asp:RadioButton ID = "RadioButton2" runat = "server" Text = "Female" GroupName = "gender" OnCheckedChanged = "RadioButton2_CheckedChanged" AutoPostBack = "True" />
        </div>
        <asp:Label ID = "Label1" runat = "server" Text = ""></asp:Label>
    </form>
    <script src = "Scripts/jquery-2.0.3.min.js"> </script>
    <script src = "Scripts/jquery-ui.min.js"> </script>
    <script>

        $(function () {
            $("#mybuttonset").buttonset();

        });
    </script>
</body>
</html>

在未套用jQuery UI Button的ButtonSet之前,外觀看起來如下:

clip_image028

圖 14:Radion伺服器控制項。

套用之後,多個Radion Button看起來如下:

clip_image030

圖 15:Radion伺服器控制項。

Tags:

.NET Magazine國際中文電子雜誌 | ASP.NET | jQuery UI | 許薰尹Vivid Hsu

新增評論




  Country flag
biuquote
  • 評論
  • 線上預覽
Loading






NET Magazine國際中文電子雜誌

NET Magazine國際中文電子版雜誌,由恆逸資訊創立於2000,自發刊日起迄今已發行超過500篇.NET相關技術文章,擁有超過40000名註冊讀者群。NET Magazine國際中文電子版雜誌希望藉於電子雜誌與NET Developer達到共同學習與技術新知分享,歡迎每一位對.NET 技術有興趣的朋友們多多支持本雜誌,讓作者群們可以有持續性的動力繼續爬文。<請加入免費訂閱>

月分類Month List