設計jQuery Mobile資料存取網頁-使用ASP.NET與ADO.NET Entity Framework(2)

by vivid 28. 八月 2013 13:30

.NET Magazine國際中文電子雜誌

者:許薰尹

稿:張智凱

文章編號:N130813903

出刊日期:2013/8/28

在前一篇「設計jQuery Mobile資料存取網頁-使用ASP.NET與ADO.NET Entity Framework(1)」文章中,介紹如何在ASP.NET網站中整合jQuery Mobile,並透過ADO.NET Entity Framework與EntityDatasource來設計能新增、刪除、修改與查詢資料庫的網頁,簡化資料存取程式碼。本文延續此篇文章的情境,改用物件服務自行撰寫程式碼來控制資料存取。

使用Entity Framework物件服務

設計jQuery Mobile網頁,修改default.aspx檔案中的程式碼,刪除以下EntityDataSource控制項的標籤:

<asp:EntityDataSource ID = "EntityDataSource1" runat = "server" ConnectionString = "name=JQMDBEntities" DefaultContainerName = "JQMDBEntities" EnableDelete = "True" EnableFlattening = "False" EnableInsert = "True" EnableUpdate = "True" EntitySetName = "Employees">

</asp:EntityDataSource>

並移除ListView控制項「DataSourceID="EntityDataSource1"」屬性,目前FormViewe控制項的開頭標籤看起來如下:

<asp:FormView ID = "FormView1" runat = "server" DataKeyNames = "EmployeeID" DefaultMode = "Edit" Width = "100%">

修改Page_Load事件處理常式程式碼,當存取到此網頁時,建立繼承自DbContext類別的JQMDBEntities物件,並進行資料查詢,讀取所有Employees資料表資料,利用資料繫結技術呈現在ListView控制項之中:

protected void Page_Load( object sender , EventArgs e ) {
        if ( Page.IsPostBack == false ) {
            JQMDBEntities context = new JQMDBEntities( );
            ListView1.DataSource = context.Employees.ToList( );
            ListView1.DataBind( );
        }
    }

JQMDBEntities類別是在建立ADO.NET Entity Data Model的edmx檔案時,由工具自動產生的程式碼,類別定義在Model.Context.cs檔案之中。

資料查詢、刪除功能測試

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

clip_image002

圖 1:讀取資料庫資料。

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

clip_image004

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

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

protected void ListView1_ItemDeleting( object sender , ListViewDeleteEventArgs e ) {
        int id = int.Parse( e.Keys [ 0 ].ToString( ) );
        JQMDBEntities context = new JQMDBEntities( );
        Employee emp = context.Employees.First( i => i.EmployeeID == id );
        context.Employees.Remove( emp );
        context.SaveChanges( );
        ListView1.DataSource = context.Employees.ToList( );
        ListView1.DataBind( );
    }

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

clip_image006

圖 3:刪除確認對話盒。

設計資料修改、新增功能

設計jQuery Mobile網頁,修改Edit.aspx檔案中的程式碼,刪除以下EntityDataSource控制項的標籤:

<asp:EntityDataSource ID = "EntityDataSource1" runat = "server" ConnectionString = "name=JQMDBEntities" DefaultContainerName = "JQMDBEntities" EnableDelete = "True" EnableFlattening = "False" EnableInsert = "True" EnableUpdate = "True" EntitySetName = "Employees"> </asp:EntityDataSource>

並移除FormView控制項「DataSourceID="EntityDataSource1"」屬性,目前FormView控制項的開頭標籤看起來如下:

<asp:FormView ID="FormView1" runat="server" DataKeyNames="EmployeeID" DefaultMode="Edit" Width="100%">

修改Page_Load事件處理常式程式碼,當存取到此網頁時,若FormView控制項為修改模式,則建立繼承自DbContext類別的JQMDBEntities物件,並進行資料查詢,讀取欲修改的那一筆Employees資料表資料,利用資料繫結技術呈現在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( ) );
            JQMDBEntities context = new JQMDBEntities( );
            Employee emp = context.Employees.First( i => i.EmployeeID == id );
            List<Employee> emps = new List<Employee>( );
            emps.Add( emp );
            FormView1.DataSource = emps;
            FormView1.DataBind( );
        }
    }

選取設計畫面上的FormView控制項,從「Properties」視窗,設定FormView控制項的事件註冊,移除ItemInserted與ItemUpdated事件註冊,然後雙擊ItemInserting與ItemUpdating項目,產生FormView1_ItemInserting與FormView1_ItemUpdating事件處理常式,請參考下圖所示:

clip_image008

圖 4:產生FormView1_ItemInserting與FormView1_ItemUpdating事件處理常式。

在FormView1_ItemInserting事件處理常式中,撰寫資料新增的程式碼,利用Entity Framework將資料新增到資料庫:

protected void FormView1_ItemInserting( object sender , FormViewInsertEventArgs e ) {
     try {
         Employee emp = new Employee {
             EmployeeID = int.Parse( e.Values [ 0 ].ToString( ) ) ,
             Name = e.Values [ 1 ].ToString( ) ,
             Age = int.Parse( e.Values [ 2 ].ToString( ) )
         };
         JQMDBEntities context = new JQMDBEntities( );
         context.Employees.Add( emp );
         context.SaveChanges( );
     } catch ( Exception ) {
     }
     Response.Redirect( "~/ default.aspx" );
}

 

在FormView1_ItemUpdating事件處理常式中加入以下程式碼,查詢出欲修改的員工資料到Employee物件,設定Name、Age屬性為新值,然後透過Entity Framework將資料變更資料庫資料:

protected void FormView1_ItemUpdating( object sender , FormViewUpdateEventArgs e ) {
    int id = int.Parse( Request.QueryString [ "id" ] );

    JQMDBEntities context = new JQMDBEntities( );
    Employee emp = context.Employees.First( i => i.EmployeeID == id );
    emp.Name = e.NewValues [ 0 ].ToString( );
    emp.Age = int.Parse( e.NewValues [ 1 ].ToString( ) );

    context.SaveChanges( );
    Response.Redirect( "~/ default.aspx" );
}

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

clip_image010

圖 5:資料更新。

若執行,點選畫面上的「新增」按鈕,就可以看到新增畫面,資料新增後,便會導向default.aspx網頁,請參考下圖所示:

clip_image012

圖 6:資料新增功能。

Default.aspx完整程式碼

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

<!DOCTYPE html>
<script runat = "server">

    protected void Page_Load( object sender , EventArgs e ) {
        if ( Page.IsPostBack == false ) {
            JQMDBEntities context = new JQMDBEntities( );
            ListView1.DataSource = context.Employees.ToList( );
            ListView1.DataBind( );
        }

    }

    protected void ListView1_ItemDeleting( object sender , ListViewDeleteEventArgs e ) {
        int id = int.Parse( e.Keys [ 0 ].ToString( ) );
        JQMDBEntities context = new JQMDBEntities( );
        Employee emp = context.Employees.First( i => i.EmployeeID == id );
        context.Employees.Remove( emp );
        context.SaveChanges( );
        ListView1.DataSource = context.Employees.ToList( );
        ListView1.DataBind( );

    }
</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#" %>

<!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( ) );
            JQMDBEntities context = new JQMDBEntities( );
            Employee emp = context.Employees.First( i => i.EmployeeID == id );
            List<Employee> emps = new List<Employee>( );
            emps.Add( emp );
            FormView1.DataSource = emps;
            FormView1.DataBind( );
        }
    }

 

    protected void FormView1_ItemUpdating( object sender , FormViewUpdateEventArgs e ) {
        int id = int.Parse( Request.QueryString [ "id" ] );

        JQMDBEntities context = new JQMDBEntities( );
        Employee emp = context.Employees.First( i => i.EmployeeID == id );
        emp.Name = e.NewValues [ 0 ].ToString( );
        emp.Age = int.Parse( e.NewValues [ 1 ].ToString( ) );

        context.SaveChanges( );
        Response.Redirect( "~/default.aspx" );
    }

    protected void FormView1_ItemInserting( object sender , FormViewInsertEventArgs e ) {
        try {
            Employee emp = new Employee {
                EmployeeID = int.Parse( e.Values [ 0 ].ToString( ) ) ,
                Name = e.Values [ 1 ].ToString( ) ,
                Age = int.Parse( e.Values [ 2 ].ToString( ) )
            };
            JQMDBEntities context = new JQMDBEntities( );
            context.Employees.Add( emp );
            context.SaveChanges( );
        } catch ( Exception ) {
        }
        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>
        $().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" DataKeyNames = "EmployeeID" DefaultMode = "Edit" Width = "100%" OnItemUpdating="FormView1_ItemUpdating" OnItemInserting="FormView1_ItemInserting">
                    <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 | jQuery Mobile | 許薰尹Vivid Hsu

新增評論




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






NET Magazine國際中文電子雜誌

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

月分類Month List