設計jQuery Mobile資料存取網頁-使用ASP.NET與ADO.NET

by vivid 1. 八月 2013 17:26

.NET Magazine國際中文電子雜誌
者:許薰尹
稿:張智凱
文章編號:N130813901
出刊日期:2013/8/1

jQuery Mobile是一個輕量型的JavaScript函式庫,提供內建的樣式表,能夠快速地設計適合行動裝置展現的網頁應用程式。本文將介紹如何在ASP.NET網站中整合jQuery Mobile,並透過ADO.NET函式庫來設計能新增、刪除、修改與查詢資料庫的網頁。

我們從頭來建立一個ASP.NET網站,開啟Visual Studio 2012,從 Visual Studio 2012的主選單點選「File」->「New」->「Web Site」,接著會開啟「New Web Site」對話窗。在對話窗裡進行以下設定:

· 「Installed」->「Templates」選Visual C#;右邊的Templates區塊中選擇「ASP.NET Empty Web Site」。

· 點選畫面右下方的「Browse…」按鈕,開啟「Choose Location」視窗,選擇「File System」,接著設定一個資料夾,請參考下圖所示:

clip_image002

圖 1:建立ASP.NET網站。

從Visual Studio 2012開發工具-「Solution Explorer」-專案名稱上方按滑鼠右鍵,從快捷選單選擇「Manage NuGet Packages」,請參考下圖所示:

clip_image004

圖 2:使用NuGet安裝jQuery、jQuery Mobile函式庫。

在「Manage NuGet Packages」對話盒右上方,輸入「jQuery」關鍵字,查詢jQuery、jQuery Mobile函式庫,並點選「Install」按鈕進行安裝,請參考下圖所示:

clip_image006

圖 3:安裝jQuery、jQuery Mobile函式庫。

設定連接字串

在這個範例中,使用SQL Server做為後端資料庫中,根據下圖所示,定義一個Employeesy資料表,來存放員工資料,請參考下圖所示:

clip_image008

圖 4:Employees資料表結構。

使用來建立Employees資料表的SQL語法如下:

CREATE TABLE [dbo].[Employees] (

[EmployeeID] INT NOT NULL,

[Name] NVARCHAR (50) NOT NULL,

[Age] INT NOT NULL,

PRIMARY KEY CLUSTERED ([EmployeeID] ASC)

);

接著在網站專案的web.config檔案中,加入connectionStrings區段描述資料庫的連接字串:

<connectionStrings>

<add name="JQMDBConnectionString" connectionString="Data Source=資料庫主機名稱;Initial Catalog=資料庫名稱;Integrated Security=True" providerName="System.Data.SqlClient"/>

</connectionStrings>

設計jQuery Mobile網頁

從Visual Studio 2012開發工具-「Solution Explorer」-專案名稱上方按滑鼠右鍵,從快捷選單選擇「Add」-「Add New Item...」,選取「Web Form」,使用預設的default.aspx檔案名稱命名,清除「Place code in separate file」核取方塊,建立網頁,請參考下圖所示:

clip_image010

圖 5:加入Web Form。

在<head>區段中引用jQuery Mobile樣式表、以及jQuery、jquery.mobile函式庫,並在<form>標籤之中,加入jQuery Mobile基本結構:

<%@ Page Language = "C#" %>
<!DOCTYPE html>
<script runat = "server">
</script>
<html xmlns = "http://www.w3.org/1999/xhtml">
<head id = "Head1" runat = "server">
    <title></title>
    <link href = "Content/jquery.mobile-1.3.1.min.css" rel = "stylesheet" />
    <script src = "Scripts/jquery-2.0.3.js"></script>
    <script src = "Scripts/jquery.mobile-1.3.1.js"></script>
</head>
<body>
<form id = "form1" runat = "server">
    <div data-role = "page" >
        <div data-role = "header" data-position = "fixed" data-theme = "b">
            <h1> jQuery Mobile </h1>
        </div>
        <!-- /header -->
        <div data-role = "content">
        </div>
        <!-- /content -->
        <div data-role = "footer" data-position = "fixed" data-theme = "b">
            <h4> ©Copyright 2013 </h4>
        </div>
        <!-- /footer -->
    </div>
   </form>
</body>
</html>

其中第一個<div>設定data-role為「page」,表示將此<div>視為一個頁面(Page);Page內三個子<div>標籤,其data-role分別設定為「header」、「content」與「footer」,代表表頭、網頁內容與表尾。

若在此階段執行網頁測試。在「Solution Explorer」-> 點選Default.aspx網頁->按滑鼠右鍵->選「View In Browser」。網頁馬上會套用jQuery Mobile的樣式,請參考下圖所示:

clip_image012

圖 6:基本的jQuery Mobile網頁。

在「data-role="content"」的div標籤之中,加入網頁元素,以下加入一個新增按鈕,以便新增員工資料:

<div data-role = "content">
  <a href = "Edit.aspx?Mode=Insert" data-icon = "plus" data-ajax = "false" data-role = "button"> 新增 </a>
<br/>
</div>


從工具箱拖曳一個ListView控制項到Default.aspx網頁「data-role="content"」的div標籤之中,請參考下圖所示:

clip_image014

圖 7:拖曳一個ListView控制項到Default.aspx網頁。

選取設計畫面上的ListView控制項,從「Properties」視窗,設定ListView控制項的DataKeyNames屬性為「EmployeeID」,請參考下圖所示:

clip_image016

圖 8:設定ListView控制項的DataKeyNames屬性。

在ListView控制項中加入AlternatingItemTemplate、EmptyDataTemplate、ItemTemplate與LayoutTemplate樣版,在樣版中使用資料繫結語法,透過Eval方法呈現取回的資料:

 

<asp:ListView ID = "ListView1" runat = "server" DataKeyNames = "EmployeeID">
    <AlternatingItemTemplate>
        <li style = "background-color: #9ACFC0">
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 員工編號: </div>
                <div class = "ui-block-b">
                    <asp:Label ID = "EmployeeIDLabel" runat = "server" Text = '<%# Eval("EmployeeID") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 員工姓名: </div>
                <div class = "ui-block-b">
                    <asp:Label ID = "NameLabel" runat = "server" Text = '<%# Eval("Name") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 年齡:</div>
                <div class = "ui-block-b">
                    <asp:Label ID = "AgeLabel" runat = "server" Text = '<%# Eval("Age") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> <a data-ajax = "false" data-icon = "grid" data-role = "button" href = 'Edit.aspx?id=<%# Eval("EmployeeID") %>'> 編輯 </a>  </div>
                <div class = "ui-block-b">
                    <asp:Button ID = "DeleteButton" data-icon = "delete" runat = "server" CommandName = "Delete" OnClientClick = "return check()" Text = "刪除" />
                </div>
            </div>
        </li>
    </AlternatingItemTemplate>
    <EmptyDataTemplate>
        未傳回資料。
    </EmptyDataTemplate>
    <ItemTemplate>
        <li style = "">
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 員工編號: </div>
                <div class = "ui-block-b">
                    <asp:Label ID = "EmployeeIDLabel" runat = "server" Text = '<%# Eval("EmployeeID") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 員工姓名: </div>
                <div class = "ui-block-b">
                    <asp:Label ID = "NameLabel" runat = "server" Text = '<%# Eval("Name") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> 年齡:</div>
                <div class = "ui-block-b">
                    <asp:Label ID = "AgeLabel" runat = "server" Text = '<%# Eval("Age") %>' />
                </div>
            </div>
            <div class = "ui-grid-a">
                <div class = "ui-block-a"> <a data-ajax = "false" data-icon = "grid" data-role = "button" href = 'Edit.aspx?id=<%# Eval("EmployeeID") %>'> 編輯 </a></div>
                <div class="ui-block-b">
                    <asp:Button ID = "DeleteButton" data-icon = "delete" runat = "server" CommandName = "Delete" OnClientClick = "return check()" Text = "刪除" />
                </div>
            </div>
        </li>
    </ItemTemplate>
    <LayoutTemplate>
        <ul id = "itemPlaceholderContainer" runat = "server" style = "" data-role = "listview">
            <li runat = "server" id = "itemPlaceholder" />
        </ul>
    </LayoutTemplate>
</asp:ListView>

 

在</head>標籤上方,加入check()函式,以設計刪除確認功能:

<script>

function check() {

return confirm("Delete?");

}

</script>

在Default.aspx網頁上方,引用System.Data.SqlClient、System.Data與System.Web.Configuration命名空間:

<%@ Import Namespace = "System.Data.SqlClient" %>

<%@ Import Namespace = "System.Data" %>

<%@ Import Namespace = "System.Web.Configuration" %>

在Page_Load事件處理常式之中,加入以下程式碼,利用WebConfigurationManager.ConnectionStrings 讀取資料庫連接字串,並透過SqlDataAdapter讀取資料庫內容,呈現在ListView控制項上:

<script runat="server">
    protected void Page_Load( object sender , EventArgs e ) {
        if ( Page.IsPostBack == false ) {
            BindListView( );
        }
    }
    private void BindListView( ) {
        SqlDataAdapter da = new SqlDataAdapter(
       "select * from Employees " ,
      WebConfigurationManager.ConnectionStrings
      [ "JQMDBConnectionString" ].ConnectionString );

        DataTable dt = new DataTable( );
        da.Fill( dt );
        ListView1.DataSource = dt;
        ListView1.DataBind( );
    }
</script>

 

 

執行網頁測試。在「Solution Explorer」->點選Default.aspx網頁->按滑鼠右鍵->選「View In Browser」。到目前為止,可以表列出資料表資料,請參考下圖所示:

clip_image018

圖 9:讀取資料庫資料。

設計資料刪除功能

選取Default.aspx設計畫面上的ListView控制項,從「Properties」視窗,點選「事件」按鈕,雙擊「ItemDeleting」項目,產生ListView控制項的ItemDeleting事件處理常式,請參考下圖所示:

clip_image020

圖 10:產生ListView控制項的ItemDeleting事件處理常式。

撰寫ListView1_ItemDeleting事件處理程式碼,利用SqlCommand物件執行資料刪除作業:

protected void ListView1_ItemDeleting( object sender , ListViewDeleteEventArgs e ) {
        int id = int.Parse( e.Keys [ 0 ].ToString( ) );
        SqlConnection cn = new SqlConnection( WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" , cn );

        cmd.Parameters.AddWithValue( "EmployeeID" , id );
        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );
        Response.Redirect( "~/default.aspx" );
    }

執行網頁測試。在「Solution Explorer」à點選Default.aspx網頁à按滑鼠右鍵à選「View In Browser」。點選任一筆資料上的「刪除」按鈕便會出現刪除確認對話盒,若按下「確定」便直接刪除資料庫資料,請參考下圖所示:

clip_image022

圖 11:刪除確認對話盒。

設計資料修改功能

從Visual Studio 2012開發工具-「Solution Explorer」-專案名稱上方按滑鼠右鍵,從快捷選單選擇「Add」-「Add New Item...」,選取「Web Form」,使用Edit.aspx命名,清除「Place code in separate file」核取方塊,建立網頁。

在<head>區段中引用jQuery Mobile樣式表、以及jQuery、jquery.mobile函式庫:

<link href = "Content/jquery.mobile-1.3.1.min.css" rel = "stylesheet" />

<script src = "Scripts/jquery-2.0.3.js"> </script>

<script src = "Scripts/jquery.mobile-1.3.1.js"> </script>

在<form>標籤之中,加入jQuery Mobile基本結構,並從「Toolbox」拖曳一個FormView控制項到Edit.aspx網頁content div之中:

<form id = "form1" runat = "server">
        <div data-role = "page">
            <div data-role = "header" data-position = "fixed" data-theme = "b">
                <h1> jQuery Mobile </h1>
            </div>
            <!-- /header -->
            <div data-role = "content">
                <asp:FormView ID = "FormView1" runat = "server" >
                </asp:FormView>
            </div>
            <!-- /content -->
            <div data-role = "footer" data-position = "fixed" data-theme = "b">
                <h4> ©Copyright 2013 </h4>
            </div>
            <!-- /footer -->
        </div>
    </form>

 

選取設計畫面上的FormView控制項,從「Properties」視窗,設定FormView控制項的「DataKeyNames」屬性為「EmployeeID」;「DefaultMode」屬性為「Edit」;「Width」屬性為「100%」,請參考下圖所示:

clip_image024

圖 12:設定FormView控制項的「DataKeyNames」屬性為「EmployeeID」。

目前FormView的標籤看起來如下:

<asp:FormView ID = "FormView1" runat = "server" DataKeyNames = "EmployeeID"

DefaultMode = "Edit" Width = "100%">

在FormView之中加入EditItemTemplate、InsertItemTemplate樣版:

<asp:FormView ID = "FormView1" runat = "server" DefaultMode = "Edit" DataKeyNames = "EmployeeID" OnItemInserting = "FormView1_ItemInserting" Width = "100%" OnItemUpdating = "FormView1_ItemUpdating">
     <EditItemTemplate>
         <div class = "ui-grid-a">
             <div class = "ui-block-a"> 員工編號:</div>
             <div class = "ui-block-b">
                 <asp:Label ID="EmployeeIDLabel1" runat = "server"
                     Text = '<%# Eval("EmployeeID") %>' />
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a"> 姓名:</div>
             <div class = "ui-block-b">
                 <asp:TextBox ID = "NameTextBox" runat = "server"
                     Text = '<%# Bind("Name") %>' />
                 <asp:RequiredFieldValidator ID = "RequiredFieldValidator1"
                     Runat = "server" ControlToValidate = "NameTextBox"
                     Display = "Dynamic" ErrorMessage = "姓名為必填欄位"> </asp:RequiredFieldValidator>
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a">年齡:</div>
             <div class = "ui-block-b">
                 <div data-role = "fieldcontain">
                     <input type = "range" name = "AgeInput" id = "AgeInput" min = "10" max = "100" />
                 </div>
                 <asp:HiddenField Value = '<%# Bind("Age") %>' ID = "AgeHiddenField" ClientIDMode = "Static" runat = "server" />
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a">
                 <asp:LinkButton data-role = "button" data-icon = "check"
                     ID = "UpdateButton" runat = "server" CausesValidation = "True"
                     CommandName = "Update" Text = "更新" />
             </div>
             <div class = "ui-block-b">
                 <a data-rel = "back" data-role = "button" data-icon = "back"> 取消 </a>
             </div>
         </div>
     </EditItemTemplate>
     <InsertItemTemplate>
         <div class = "ui-grid-a">
             <div class = "ui-block-a"> 員工編號:</div>
             <div class = "ui-block-b">
                 <asp:TextBox ID = "EmployeeIDTextBox" runat = "server"
                     Text = '<%# Bind("EmployeeID") %>' />
                 <asp:RequiredFieldValidator ID = "RequiredFieldValidator2"
                     runat = "server" ControlToValidate = "EmployeeIDTextBox"
                     Display = "Dynamic"
                     ErrorMessage = "編號為必填欄位"> </asp:RequiredFieldValidator>
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a"> 姓名:</div>
             <div class = "ui-block-b">
                 <asp:TextBox ID = "NameTextBox" runat = "server"
                     Text = '<%# Bind("Name") %>' />
                 <asp:RequiredFieldValidator ID = "RequiredFieldValidator1"
                     runat = "server" ControlToValidate = "NameTextBox"
                     Display = "Dynamic"
                     ErrorMessage = "姓名為必填欄位"> </asp:RequiredFieldValidator>
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a"> 年齡:</div>
             <div class = "ui-block-b">
                 <div data-role = "fieldcontain">
                     <input type = "range" name = "AgeInput" id = "AgeInput" value = "25" min = "10" max = "100" />
                 </div>
                 <asp:HiddenField Value = '<%# Bind("Age") %>' ID = "AgeHiddenField" ClientIDMode = "Static" runat = "server" />
             </div>
         </div>
         <div class = "ui-grid-a">
             <div class = "ui-block-a">
                 <asp:LinkButton data-role = "button" data-icon = "plus"
                     ID = "InsertButton" runat = "server" CausesValidation = "True"
                     CommandName = "Insert" Text = "新增" />
             </div>
             <div class = "ui-block-b">
                 <a data-rel = "back" data-role = "button" data-icon = "back"> 取消 </a>
             </div>
         </div>
     </InsertItemTemplate>
</asp:FormView>

 

在Edit.aspx網頁上方,引用System.Data.SqlClient、System.Data與System.Web.Configuration命名空間:

<%@ Import Namespace = "System.Data.SqlClient" %>

<%@ Import Namespace = "System.Data" %>

<%@ Import Namespace = "System.Web.Configuration" %>

在Page_Load事件處理常式之中,加入以下程式碼,利用WebConfigurationManager.ConnectionStrings 讀取資料庫連接字串,並透過SqlDataAdapter讀取資料庫內容,呈現在FormView控制項上:

protected void Page_Load( object sender , EventArgs e ) {
    if ( Request.QueryString [ "mode" ] != null ) {
        FormView1.DefaultMode = FormViewMode.Insert;
    }
    if ( Page.IsPostBack == false && Request.QueryString [ "id" ] !=null) {
        int id = int.Parse( Request.QueryString [ "id" ].ToString( ) );
        BindListView( id );
    }
}
private void BindListView( int id ) {
    SqlDataAdapter da = new SqlDataAdapter(
   "select * from Employees where  [EmployeeID] = @EmployeeID" ,
  WebConfigurationManager.ConnectionStrings
  [ "JQMDBConnectionString" ].ConnectionString );

    da.SelectCommand.Parameters.AddWithValue( "EmployeeID" , id );
    DataTable dt = new DataTable( );
    da.Fill( dt );
    FormView1.DataSource = dt;
    FormView1.DataBind( );
}

 

 

選取Edit.aspx設計畫面上的ListView控制項,從「Properties」視窗,點選「事件」按鈕,雙擊「ItemInserting」項目,產生FormView控制項的ItemInserting事件處理常式,並加入以下程式碼,新增資料到資料庫:

protected void FormView1_ItemInserting( object sender , FormViewInsertEventArgs e ) {
        int id = int.Parse( e.Values [ 0 ].ToString( ) );
        string name = e.Values [ 1 ].ToString( );
        int age = int.Parse( e.Values [ 2 ].ToString( ) );

        SqlConnection cn = new SqlConnection(
  WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "INSERT INTO [Employees] ([EmployeeID], [Name], [Age]) VALUES (@EmployeeID, @Name, @Age)" , cn );
        cmd.Parameters.AddWithValue( "Name" , name );
        cmd.Parameters.AddWithValue( "Age" , age );
        cmd.Parameters.AddWithValue( "EmployeeID" , id );
        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );
        Response.Redirect( "~/List.aspx" );

    }

 

 

重複上個步驟,選取Edit.aspx設計畫面上的ListView控制項,從「Properties」視窗,點選「事件」按鈕,雙擊「ItemUpdating」項目,產生FormView控制項的ItemUpdating事件處理常式,並加入以下程式碼,更改資料資料庫資料:

protected void FormView1_ItemUpdating( object sender , FormViewUpdateEventArgs e ) {
        string id = Request.QueryString [ "id" ];
        string name = e.NewValues [ 0 ].ToString( );
        int age = int.Parse( e.NewValues [ 1 ].ToString( ) );

        SqlConnection cn = new SqlConnection(
  WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "UPDATE [Employees] SET [Name] = @Name, [Age] = @Age WHERE [EmployeeID] = @EmployeeID" , cn );

        cmd.Parameters.AddWithValue( "Name" , name );
        cmd.Parameters.AddWithValue( "Age" , age );
        cmd.Parameters.AddWithValue( "EmployeeID" , id );

        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );

        Response.Redirect( "~/Default.aspx" );

    }

 

在</head>標籤上方,加入jQuery ready事件,當使用者拖曳代表年齡的水平滑桿控制項時,能將值儲存到隱藏欄位中:

<script>
    $().ready(function () {
        $("#AgeInput").val($("#AgeHiddenField").val());
        $("#AgeInput").slider('refresh');

        $('#AgeInput').change(function () {
            $("#AgeHiddenField").val($(this).val());
        })
    });
</script>

 

修改web.config檔案,關閉UnobtrusiveValidationMode模式:

<appSettings>

<add key="ValidationSettings:UnobtrusiveValidationMode" value="none" />

</appSettings>

 

執行網頁測試。在「Solution Explorer」->點選Default.aspx網頁->按滑鼠右鍵à選「View In Browser」。點選表列出的任一筆資料表資料上的「編輯」按鈕,就進入資料編輯模式,可進一步修改資料,請參考下圖所示:

clip_image028

圖 14:資料更新。

Default.aspx完整程式碼:

<%@ Import Namespace = "System.Data.SqlClient" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Web.Configuration" %>

<!DOCTYPE html>

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

<script runat="server">
    protected void Page_Load( object sender , EventArgs e ) {
        if ( Page.IsPostBack == false ) {
            BindListView( );
        }
    }
    private void BindListView( ) {
        SqlDataAdapter da = new SqlDataAdapter(
       "select * from Employees " ,
      WebConfigurationManager.ConnectionStrings
      [ "JQMDBConnectionString" ].ConnectionString );

        DataTable dt = new DataTable( );
        da.Fill( dt );
        ListView1.DataSource = dt;
        ListView1.DataBind( );
    }

    protected void ListView1_ItemDeleting( object sender , ListViewDeleteEventArgs e ) {
        int id = int.Parse( e.Keys [ 0 ].ToString( ) );
        SqlConnection cn = new SqlConnection( WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" , cn );

        cmd.Parameters.AddWithValue( "EmployeeID" , id );
        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );
        Response.Redirect( "~/default.aspx" );

    }
</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head id = "Head1" runat = "server">
    <title> </title>
    <link href = "Content/jquery.mobile-1.3.1.min.css" rel = "stylesheet" />
    <script src = "Scripts/jquery-2.0.3.js"> </script>
    <script src = "Scripts/jquery.mobile-1.3.1.js"> </script>
    <script>
        function check() {
            return confirm("Delete?");
        }
    </script>

</head>
<body>
    <form id = "form1" runat = "server">
        <div data-role = "page">
            <div data-role = "header" data-position = "fixed" data-theme = "b">
                <h1> jQuery Mobile </h1>
            </div>
            <!-- /header -->
            <div data-role = "content">
                <a href = "Edit.aspx?Mode=Insert" data-icon = "plus" data-ajax = "false" data-role = "button"> 新增 </a>
                <br />
                <asp:ListView ID = "ListView1" runat = "server" DataKeyNames = "EmployeeID" OnItemDeleting = "ListView1_ItemDeleting">
                    <AlternatingItemTemplate>
                        <li style = "background-color: #9ACFC0">
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a">員工編號:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "EmployeeIDLabel" runat = "server" Text = '<%# Eval("EmployeeID") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> 員工姓名:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "NameLabel" runat = "server" Text = '<%# Eval("Name") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> 年齡:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "AgeLabel" runat = "server" Text = '<%# Eval("Age") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> <a data-ajax = "false" data-icon = "grid" data-role = "button" href = 'Edit.aspx?id=<%# Eval("EmployeeID") %>'> 編輯</a></div>
                                <div class = "ui-block-b">
                                    <asp:Button ID = "DeleteButton" data-icon = "delete" runat = "server" CommandName = "Delete" OnClientClick = "return check()" Text = "刪除" />
                                </div>
                            </div>
                        </li>
                    </AlternatingItemTemplate>
                    <EmptyDataTemplate>
                        未傳回資料。
                    </EmptyDataTemplate>
                    <ItemTemplate>
                        <li style = "">
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> 員工編號:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "EmployeeIDLabel" runat = "server" Text = '<%# Eval("EmployeeID") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> 員工姓名:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "NameLabel" runat = "server" Text = '<%# Eval("Name") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> 年齡:</div>
                                <div class = "ui-block-b">
                                    <asp:Label ID = "AgeLabel" runat = "server" Text = '<%# Eval("Age") %>' />
                                </div>
                            </div>
                            <div class = "ui-grid-a">
                                <div class = "ui-block-a"> <a data-ajax = "false" data-icon = "grid" data-role = "button" href = 'Edit.aspx?id=<%# Eval("EmployeeID") %>'> 編輯</a></div>
                                <div class = "ui-block-b">
                                    <asp:Button ID = "DeleteButton" data-icon = "delete" runat = "server" CommandName = "Delete" OnClientClick = "return check()" Text = "刪除" />
                                </div>
                            </div>
                        </li>
                    </ItemTemplate>
                    <LayoutTemplate>
                        <ul id = "itemPlaceholderContainer" runat = "server" style = "" data-role = "listview">
                            <li runat = "server" id = "itemPlaceholder" />
                        </ul>
                    </LayoutTemplate>
                </asp:ListView>

            </div>
            <!-- /content -->
            <div data-role = "footer" data-position = "fixed" data-theme = "b">
                <h4> ©Copyright 2013 </h4>
            </div>
            <!-- /footer -->
        </div>
    </form>
</body>
</html>

 

Edit.aspx完整程式碼:

<%@ Page Language="C#" %>
<%@ Import Namespace = "System.Data.SqlClient" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "System.Web.Configuration" %>
<!DOCTYPE html>
<script runat="server">
    protected void Page_Load( object sender , EventArgs e ) {
        if ( Request.QueryString [ "mode" ] != null ) {
            FormView1.DefaultMode = FormViewMode.Insert;
        }
        if ( Page.IsPostBack == false && Request.QueryString [ "id" ] != null ) {
            int id = int.Parse( Request.QueryString [ "id" ].ToString( ) );
            BindListView( id );
        }
    }
    private void BindListView( int id ) {
        SqlDataAdapter da = new SqlDataAdapter(
       "select * from Employees where  [EmployeeID] = @EmployeeID" ,
      WebConfigurationManager.ConnectionStrings
      [ "JQMDBConnectionString" ].ConnectionString );

        da.SelectCommand.Parameters.AddWithValue( "EmployeeID" , id );
        DataTable dt = new DataTable( );
        da.Fill( dt );
        FormView1.DataSource = dt;
        FormView1.DataBind( );
    }
    protected void FormView1_ItemInserting( object sender , FormViewInsertEventArgs e ) {
        int id = int.Parse( e.Values [ 0 ].ToString( ) );
        string name = e.Values [ 1 ].ToString( );
        int age = int.Parse( e.Values [ 2 ].ToString( ) );

        SqlConnection cn = new SqlConnection(
  WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "INSERT INTO [Employees] ([EmployeeID], [Name], [Age]) VALUES (@EmployeeID, @Name, @Age)" , cn );
        cmd.Parameters.AddWithValue( "Name" , name );
        cmd.Parameters.AddWithValue( "Age" , age );
        cmd.Parameters.AddWithValue( "EmployeeID" , id );
        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );
        Response.Redirect( "~/List.aspx" );

    }
    protected void FormView1_ItemUpdating( object sender , FormViewUpdateEventArgs e ) {
        string id = Request.QueryString [ "id" ];
        string name = e.NewValues [ 0 ].ToString( );
        int age = int.Parse( e.NewValues [ 1 ].ToString( ) );

        SqlConnection cn = new SqlConnection(
  WebConfigurationManager.ConnectionStrings [ "JQMDBConnectionString" ].ConnectionString );

        SqlCommand cmd = new SqlCommand(
            "UPDATE [Employees] SET [Name] = @Name, [Age] = @Age WHERE [EmployeeID] = @EmployeeID" , cn );

        cmd.Parameters.AddWithValue( "Name" , name );
        cmd.Parameters.AddWithValue( "Age" , age );
        cmd.Parameters.AddWithValue( "EmployeeID" , id );

        cn.Open( );
        cmd.ExecuteNonQuery( );
        cn.Close( );

        Response.Redirect( "~/Default.aspx" );

    }

</script>

<html xmlns = "http://www.w3.org/1999/xhtml">
<head runat = "server">
    <title></title>
    <link href = "Content/jquery.mobile-1.3.1.min.css" rel = "stylesheet" />
    <script src = "Scripts/jquery-2.0.3.js"></script>
    <script src = "Scripts/jquery.mobile-1.3.1.js"></script>
    <script>
        $().ready(function () {
            $("#AgeInput").val($("#AgeHiddenField").val());
            $("#AgeInput").slider('refresh');

            $('#AgeInput').change(function () {
                $("#AgeHiddenField").val($(this).val());
            })
        });
    </script>

</head>
<body>
    <form id = "form1" runat = "server">
        <div data-role = "page">
            <div data-role = "header" data-position = "fixed" data-theme = "b">
                <h1>jQuery Mobile</h1>
            </div>
            <!-- /header -->
            <div data-role = "content">
                <asp:FormView ID = "FormView1" runat = "server" DefaultMode = "Edit" DataKeyNames = "EmployeeID" OnItemInserting = "FormView1_ItemInserting" Width = "100%" OnItemUpdating = "FormView1_ItemUpdating">
                    <EditItemTemplate>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">員工編號:</div>
                            <div class = "ui-block-b">
                                <asp:Label ID = "EmployeeIDLabel1" runat = "server"
                                    Text = '<%# Eval("EmployeeID") %>' />
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">姓名:</div>
                            <div class = "ui-block-b">
                                <asp:TextBox ID = "NameTextBox" runat = "server"
                                    Text = '<%# Bind("Name") %>' />
                                <asp:RequiredFieldValidator ID = "RequiredFieldValidator1"
                                    runat = "server" ControlToValidate = "NameTextBox"
                                    Display = "Dynamic" ErrorMessage = "姓名為必填欄位"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">年紀:</div>
                            <div class = "ui-block-b">
                                <div data-role = "fieldcontain">
                                    <input type = "range" name = "AgeInput" id = "AgeInput" min = "10" max = "100" />
                                </div>
                                <asp:HiddenField Value = '<%# Bind("Age") %>' ID = "AgeHiddenField" ClientIDMode = "Static" runat = "server" />
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">
                                <asp:LinkButton data-role = "button" data-icon = "check"
                                    ID = "UpdateButton" runat = "server" CausesValidation = "True"
                                    CommandName = "Update" Text = "更新" />
                            </div>
                            <div class = "ui-block-b">
                                <a data-rel = "back" data-role = "button" data-icon =  "back">取消</a>
                            </div>
                        </div>
                    </EditItemTemplate>
                    <InsertItemTemplate>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">員工編號:</div>
                            <div class = "ui-block-b">
                                <asp:TextBox ID = "EmployeeIDTextBox" runat="server"
                                    Text = '<%# Bind("EmployeeID") %>' />
                                <asp:RequiredFieldValidator ID = "RequiredFieldValidator2"
                                    Runat = "server" ControlToValidate = "EmployeeIDTextBox"
                                    Display = "Dynamic"
                                    ErrorMessage = "編號為必填欄位"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">姓名:</div>
                            <div class = "ui-block-b">
                                <asp:TextBox ID = "NameTextBox" runat = "server"
                                    Text = '<%# Bind("Name") %>' />
                                <asp:RequiredFieldValidator ID = "RequiredFieldValidator1"
                                    runat = "server" ControlToValidate = "NameTextBox"
                                    Display = "Dynamic"
                                    ErrorMessage = "姓名為必填欄位"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">年齡:</div>
                            <div class = "ui-block-b">
                                <div data-role = "fieldcontain">
                                    <input type = "range" name = "AgeInput" id = "AgeInput" value = "25" min = "10" max = "100" />
                                </div>
                                <asp:HiddenField Value = '<%# Bind("Age") %>' ID = "AgeHiddenField" ClientIDMode = "Static" runat = "server" />
                            </div>
                        </div>
                        <div class = "ui-grid-a">
                            <div class = "ui-block-a">
                                <asp:LinkButton data-role = "button" data-icon = "plus"
                                    ID = "InsertButton" runat = "server" CausesValidation = "True"
                                    CommandName = "Insert" Text = "新增" />
                            </div>
                            <div class = "ui-block-b">
                                <a data-rel = "back" data-role = "button" data-icon = "back">取消</a>
                            </div>
                        </div>
                    </InsertItemTemplate>
                </asp:FormView>

            </div>
            <!-- /content -->
            <div data-role = "footer" data-position = "fixed" data-theme = "b">
                <h4> ©Copyright 2013 </h4>
            </div>
            <!-- /footer -->
        </div>
    </form>

</body>
</html>

Tags:

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

新增評論




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






NET Magazine國際中文電子雜誌

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

月分類Month List