Cấp bậc tác giả:

TRAINING

[TUT .netTiers]Giới thiệu Lớp Web ASP.NET

Được viết bởi webmaster ngày 07/06/2013 lúc 10:53 AM
Bài trước Tôi đã giới thiệu về Lớp Business. Là nơi tập trung quy trình nghiệp vụ, quy trình làm việc, ủy quyền, huyết mạch ứng dụng, và API dữ liệu. Bài này Tôi sẽ giới thiệu về Lớp Web.
  • 0
  • 7992

[TUT .netTiers]Giới thiệu Lớp Web ASP.NET

Bài trước Tôi đã giới thiệu về Lớp Business. Là nơi tập trung quy trình nghiệp vụ, quy trình làm việc, ủy quyền, huyết mạch ứng dụng, và API dữ liệu. Bài này Tôi sẽ giới thiệu về Lớp Web.

Thư viện web

Thư viện Web NetTiers là tập hợp điều khiển và các đối tượng cung cấp công cụ mạnh mẽ để thực hiện các dự án phát triển web với NetTiers dễ dàng hơn và hiệu quả hơn.

Kiểu DataSource Control so với EntityDataSource

Thư viện Web cung cấp cả kiểu DataSource Control mạnh mẽ cũng như các chi tiết chung chung EntityDataSource. Các kiểu DataSource Control mạnh mẽ là rất lớn bởi vì bằng cách gắn vào chúng, bạn phải tính tất cả các đối tượng và phương thức xác định trước và theo ý của bạn. Tất cả điều này cho thấy trong IntelliSense. Những phần chính ObjectDataSource control mô hình sự kiện, chúng hướng đến dữ liệu, các mối quan hệ, và tên miền. Mặt khác, EntityDataSource control là một nguồn dữ liệu chung chung và rất hữu ích bởi vì nó sử dụng 100% phản ánh để làm việc với cung cấp dữ liệu. Điều này là tuyệt vời khi bạn cần phải thay đổi kiểu trong Runtime, hoặc có thể bạn đã viết phương thức riêng trong DataAccessLayer mà bạn muốn gọi, sau đó bạn chỉ cần sử dụng EntityDataSource Control.

Giao diện người dùng Control

Thư viện web thêm một bộ sưu tập các giao diện người dùng điều khiển vào hộp công cụ của bạn chẳng hạn như các bộ lặp mạnh mẽ ràng buộc, EntityGridView, EntityDropDownList, BoundRadioButtonField, HyperlinkField, EntityLabel và GridViewSearchPanel.

Cấu hình Web.Config 

Để sử dụng Thư viện Web NetTiers bạn sẽ cần phải thêm một chuỗi kết nối ...

<configuration>
  <connectionStrings>
    <add name="Northwind.Data.ConnectionString" connectionString="..." />
  </connectionStrings>
</configuration>

và đăng ký control web

 <configuration>
   <system.web>
     <pages>
       <controls>
         <!-- register web controls for use on all pages -->
         <add tagPrefix="data" namespace="Northwind.Web.Data" assembly="Northwind.Web"/>
         <add tagPrefix="data" namespace="Northwind.Web.UI" assembly="Northwind.Web"/>
       </controls>
     </pages>
  </system.web>
</configuration>

và cấu hình quản lý giao dịch

<configuration>
  <system.web>
    <httpModules>
      <!--
        Enable transaction-per-request pattern;  
        This module allows a single TransactionManager to be shared by
        all data access operations executed during a page request.  
        Used by the EntityDataSource control when
        the EntityDataSource.EnableTransaction property is set to True.
      -->
      <add name="EntityTransactionModule" 
            type="Northwind.Web.Data.EntityTransactionModule, Northwind.Web"/>
    </httpModules>
  </system.web>
</configuration>

và thêm config section

<configuration>
  <configSections>
    <section name="Northwind.Data" type="Northwind.Data.Bases.NetTiersServiceSection, 
      Northwind.Data" allowDefinition="MachineToApplication" 
      restartOnExternalChanges="true" />
  </configSections>
  <Northwind.Data defaultProvider="SqlNetTiersProvider">
    <providers>
      <add
        name="SqlNetTiersProvider"
        type="Northwind.Data.SqlClient.SqlNetTiersProvider, Northwind.Data.SqlClient"
        connectionStringName="Northwind.Data.ConnectionString"
        providerInvariantName="System.Data.SqlClient"
        entityFactoryType="Northwind.Entities.EntityFactory"
        useEntityFactory="true"
        enableEntityTracking="true"
        enableMethodAuthorization="false"
        useStoredProcedure="false"
        defaultCommandTimeout="30"/>
    </providers>
  </Northwind.Data>
</configuration>

Đừng quên thêm tham chiếu đến dữ liệu, thực thể của bạn, và các dự án Web, bằng cách nhấn chuột phải vào dự án web/website và chọn "Add Reference".

Sử dụng Kiểu DataSource Controls

PS_14_WebForm1.gif

Productivity Enabler: Khi bạn chọn các thuộc tính SelectMethod, bạn sẽ thấy thông qua IntelliSense danh sách của tất cả các phương thức từ miền có sẵn.

PS_14_WebForm2.gif

Ví dụ WebForm đơn giản: Dưới đây là ví dụ về Webform đơn giản, hiển thị lưới(grid) của tất cả các nhân viên với các cột tự động tạo ra. 

PS_14_WebForm3.gif

Xem chế độ Design: Lấy Form và chỉ chọn những cột mà tôi muốn, tạo ra giao diện lưới đẹp. 

PS_14_WebForm4Designc.gif

Kết quả Data View:
Đây là kết quả của Form. Phần tuyệt vời của kiểu DataSource Control là bạn không phải làm bất cứ điều gì khi bạn muốn chỉnh sửa/thêm/xóa đối tượng. Bạn chỉ cần có lưới(grid) gọi edit/insert/delete, có thể được thực hiện nhiều cách khác nhau trong ASP.net.

PS_14_WebForm4DesignResults.gif
Kết quả

PS_14_WebForm4Edit.gif
Edit

PS_14_WebForm4EditComplete.gif
Sau khi Edit
TypedDataSource với Microsoft AJAX

GridView Paging, Sorting và Update/Delete

TypedDatasourceGridView.gif

Tạo Grid

Đầu tiên, tạo trang mới và thêm điều khiển GridView: 
Chú ý: Nó rất quan trọng ở chỗ bạn phải xác định thuộc tính DataKeyNames của GridView, nếu không, Insert/Update/Delete sẽ không làm việc.

<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server"
       DataSourceID="CustomersDataSource1" 
       DataKeyNames="CustomerID"   
       PageSize="10" AllowPaging="true" AllowSorting="true">
   <Columns>
      <asp:CommandField ShowEditButton="True" />
      <asp:BoundField DataField="CustomerID" HeaderText="Cust #" SortExpression="CustomerID" />
      <asp:BoundField DataField="CompanyName" 
            HeaderText="Company" SortExpression="CompanyName" />
      <asp:BoundField DataField="ContactTitle" HeaderText="Title" SortExpression="ContactTitle" />
      <asp:BoundField DataField="ContactName" HeaderText="Name" 
            SortExpression="ContactName" />
      <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
      <asp:BoundField DataField="Region" HeaderText="Region" SortExpression="Region" />
      <asp:BoundField DataField="PostalCode" HeaderText="Postal Code" 
            SortExpression="PostalCode" />
      <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
      <asp:CommandField ShowDeleteButton="true" />
   </Columns>
</asp:GridView>
<code>

Tiếp theo, thêm Control CustomersDataSource vào trang web của bạn:

<data:CustomersDataSource ID="CustomersDataSource1" 
   runat="server"
   SelectMethod="GetPaged" 
   EnablePaging="true" 
   EnableSorting="true"/>

Và bạn sẽ có GridView với chức năng phân trang và sắp xếp!

<code lang="XML" linenumbers="true">
<table border="0" width="310" style="margin-bottom:10px;">
<tr>
   <td>
      <asp:Label ID="CountryLabel" 
            AssociatedControlID="CountryList" runat="server" Text="Country:" />
   </td>
   <td>
      <asp:DropDownList ID="CountryList" AutoPostBack="true" runat="server">
            <asp:ListItem Value="">All</asp:ListItem>
            <asp:ListItem>Brazil</asp:ListItem>
            <asp:ListItem>Canada</asp:ListItem>
            <asp:ListItem>France</asp:ListItem>
            <asp:ListItem>Germany</asp:ListItem>
            <asp:ListItem>Italy</asp:ListItem>
            <asp:ListItem>Mexico</asp:ListItem>
            <asp:ListItem>Spain</asp:ListItem>
            <asp:ListItem>UK</asp:ListItem>
            <asp:ListItem>USA</asp:ListItem>
            <asp:ListItem>Venezuela</asp:ListItem>
      </asp:DropDownList>
   </td>
   <td align="right">
      <asp:Label ID="TimeLabel" runat="server" Font-Names="Verdana" Font-Size="10px">
            <%= DateTime.Now %/></asp:Label>
   </td>
</tr>
</table>

Tiếp theo, thay đổi data source control ở trên để thêm một tham số cho các tham số whereClause của phương thức GetPaged. Các SqlParameter cho phép bạn xác định điều khiển bộ lọc bên ngoài sẽ được kết hợp để tạo ra các biểu thức lọc:

<data:CustomersDataSource ID="CustomersDataSource1" runat="server"
   SelectMethod="GetPaged" EnablePaging="true" EnableSorting="true">
   <Parameters>
      <data:SqlParameter Name="WhereClause" UseParameterizedFilters="false">
         <Filters>
            <data:CustomersFilter Column="Country" ControlID="CountryList" />
         </Filters>
      </data:SqlParameter>
   </Parameters>
</data:CustomersDataSource>

AJAX Magic: Bây giờ chúng ta có thể thêm công nghệ AJAX vào! Hãy chắc chắn rằng bạn có tham chiếu đến các AJAX Script Manager:

<atlas:ScriptManager ID="ScriptManager1" EnablePartialRendering="true" runat="server" />

Giờ bọc điều khiển GridView với UpdatePanel:

<asp:UpdatePanel ID="GridPanel" UpdateMode="Conditional" runat="server">
   <ContentTemplate>

      <!-- GridView declaration goes here -->

   </ContentTemplate>
   <Triggers>
      <atlas:ControlEventTrigger ControlID="CountryList" EventName="SelectedIndexChanged" />
   </Triggers>
</asp:UpdatePanel>

Trigger gắn liền với điều khiển CountryList để GridView được cập nhật mỗi lần chọn thay đổi.

Sử dụng điều khiển EntityDataSource

Điều khiển EntityDataSource là cách tốt nhất vì nó sử dụng 100% reflection để làm việc với các cung cấp dữ liệu. Điều này là tốt khi bạn cần phải thay đổi kiểu trong Runtime, hoặc có thể bạn đã viết phương thức riêng của bạn trong DataAccessLayer mà bạn muốn gọi. Bạn chỉ cần sử dụng điều khiển EntityDataSource.

<data:EntityDataSource ID="dataSourceID" runat="server"
   TypeName="Namespace.Data.DataRepository, Namespace.Data"
   TypeProperty=""
   ProviderName=""
   EntityTypeName=""
   EntityKeyTypeName="System.Guid"
   EntityKeyName=""
   SelectMethod="GetAll"
   InsertMethod="Insert"
   UpdateMethod="Update"
   DeleteMethod="Delete"
   EnablePaging="false"
   EnableSorting="false"
   EnableTransaction="true"
   InsertDateTimeNames=""
   UpdateDateTimeNames=""
   Filter=""
   Sort=""

   OnSelecting=""
   OnSelected=""
   OnInserting=""
   OnInserted=""
   OnUpdating=""
   OnUpdated=""
   OnDeleting=""
   OnDeleted=""
>
   <Parameters>
   </Parameters>
</data:EntityDataSource>
  • ProviderName (yêu cầu) - một bí danh cho TypeProperty, tên thuộc tính tĩnh của lớp DataRepository trả về tham chiếu đến provider cụ thể. Ví dụ: ProviderName = "CustomersProvider" đối với Northwind.Data.DataRepository.CustomersProvider
  • EntityTypeName (bắt buộc) - tên lớp đầy đủ của lớp thực thể được xử lý bởi cung cấp dữ liệu cụ thể.
  • EntityKeyName - tên của thuộc tính chứa giá trị khóa chính.
  • EntityKeyTypeName - tên lớp đầy đủ cho các kiểu trả về thuộc tính EntityKeyName.
  • EnableTransaction - thiết lập để True nếu EntityDataSource dựa vào các lớp EntityTransactionModule cung cấp đối tượng TransactionManager.
  • InsertDateTimeNames - danh sách bằng dấu phẩy của tên thuộc tính datetime để khởi tạo với giá trị DateTime.Now hiện tại trong chèn.
  • UpdateDateTimeNames - danh sách bằng dấu phẩy của tên thuộc tính datetime để khởi tạo với giá trị DateTime.Now hiện tại trong cập nhật.
  • Filter - giá trị để áp dụng cho các thuộc tính ListBase.Filter sau khi chọn (nếu EnablePaging là false)
  • Sort - giá trị của tham số vượt qua các phương thức ListBase.Sort(string) sau khi chọn (nếu EnableSorting là false)

Ví dụ: Đây là ví dụ về điều khiển phổ biến DropDownList với dữ liệu lấy ra bằng cách sử dụng điều khiển EntityDataSource.

<asp:Label ID="ShipViaLabel" runat="server" Text="Ship Via" AssociatedControlID="ShipViaList" />

<asp:DropDownList ID="ShipViaList" runat="server"
    SelectedValue='<%# Bind("ShipVia") %>'
    AppendDataBoundItems="True"
    DataSourceID="ShippersDataSource"
    DataTextField="CompanyName"
    DataValueField="ShipperID"
>
    <!-- an empty ListItem along with the AppendDataBoundItems property allow for a nullable relationship -->
    <asp:ListItem Value="" Text="" />
</asp:DropDownList>

<data:EntityDataSource ID="ShippersDataSource" runat="server"
    ProviderName="ShippersProvider"
    EntityTypeName="Northwind.BLL.Shippers, Northwind.BLL"
    EntityKeyTypeName="System.Int32"
    SelectMethod="GetAll"
    Sort="CompanyName ASC"
/>  

Sử dụng nhiều quan hệ Controls điều khiển ManyToManyListRelationship quản lý bảng junction liên kết thực thể chính với bảng khóa ngoại.

<asp:FormView ID="FormView1" runat="server" DataSourceID="CustomersDataSource" DefaultMode="Edit">
    <EditItemTemplate>
        <table border="0">
        <tr>
            <td>Cust #:</td>
            <td><asp:Label ID="CustomerIDLabel" runat="server" Text='<%# Bind("CustomerID") %>' /></td>
        </tr>
        <tr>
            <td>Company Name:</td>
            <td><asp:TextBox ID="CompanyNameTextBox" runat="server" Text='<%# Bind("CompanyName") %>' /></td>
        </tr>
        <tr>
            <td valign="top">Demographics:</td>
            <td>
                <!-- the visual representation of the many-to-many relationship -->
                <asp:CheckBoxList ID="CustomerDemographicsList" runat="server"
                    DataSourceID="CustomerDemographicsDataSource"
                    DataTextField="CustomerDesc"
                    DataValueField="CustomerTypeID"
                />
                
                <!-- provides the list of available data for the relationship -->
                <data:EntityDataSource ID="CustomerDemographicsDataSource" runat="server"
                    ProviderName="CustomerDemographicsProvider"
                    EntityTypeName="Northwind.BLL.CustomerDemographics, Northwind.BLL"
                    SelectMethod="GetAll"
                    Filter="CustomerDesc != 'Temporary'"
                    Sort="CustomerDesc ASC"
                />
                
                <!-- provides management of the link table -->
                <data:EntityDataSource ID="CustomerCustomerDemoDataSource" runat="server"
                    ProviderName="CustomerCustomerDemoProvider"
                    EntityTypeName="Northwind.BLL.CustomerCustomerDemo, Northwind.BLL"
                    EntityKeyTypeName="System.String"
                    SelectMethod="GetByCustomerID"
                >
                    <Parameters>
                        <asp:QueryStringParameter Name="EntityId" QueryStringField="id" />
                    </Parameters>
                </data:EntityDataSource>
                
                <!--
                    The relationship controls hook one or more EntityDataSource controls to the 
                    EntityDataSource specified by the PrimaryMember.EntityDataSourceID property.
                    This allows multiple insert/update operations to be executed during a single
                    form submission.
                -->
                <data:ManyToManyListRelationship ID="CustomerCustomerDemoRelationship" runat="server">
                    <%-- represents the Customers table --%>
                    <PrimaryMember runat="server"
                        DataSourceID="CustomersDataSource"
                        EntityKeyName="CustomerID"
                    />
                    <%-- represents the CustomerCustomerDemo link table --%>
                    <LinkMember runat="server"
                        DataSourceID="CustomerCustomerDemoDataSource"
                        EntityKeyName="CustomerID"
                        ForeignKeyName="CustomerTypeID"
                    />
                    <%-- represents the CustomerDemographics table --%>
                    <ReferenceMember runat="server"
                        DataSourceID="CustomerDemographicsDataSource"
                        ListControlID="CustomerDemographicsList"
                        EntityKeyName="CustomerTypeID"
                    />
                </data:ManyToManyListRelationship>
            </td>
        </tr>
        </table>
    </EditItemTemplate>
    
    <FooterTemplate>
        <asp:Button ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="Update" />
        <asp:Button ID="CancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" />
    </FooterTemplate>
</asp:FormView>

<!-- primary entity data source -->
<data:EntityDataSource ID="CustomersDataSource" runat="server"
    ProviderName="CustomersProvider"
    EntityTypeName="Northwind.BLL.Customers, Northwind.BLL"
    EntityKeyTypeName="System.String"
    EntityKeyName="CustomerID"
    SelectMethod="GetByCustomerID"
>
    <Parameters>
        <asp:QueryStringParameter Name="EntityId" QueryStringField="id" Type="String" />
    </Parameters>
</data:EntityDataSource> 

ManyToManyWithRelationship.gif

EntityDropDownList và kết hợp BoundEntityDropDownField

EntityDropDownList - xuất phát từ một DropDownList, nhưng bổ sung thêm một vài tính năng chẳng hạn như khả năng thêm một mục rỗng (thêm child ListItem), làm cho nó chỉ đọc (chuyển nó đến nhãn), làm cho điều khiển bắt buộc (sử dụng RequiredFieldValidator) và nó hỗ trợ kiểu  ahead(javascript). 

Ví dụ sử dụng:

<data:EntityDropDownList runat="server" ID="myfieldDDL" 
     DataSourceID="productsDataSource"  
     DataTextField="ProductName" 
     DataValueField="ProductID"
     AppendNullItem="true" 
     NullItemText="<select a value>"
     Required="true"
     ReadOnly="false"
     FriendlyName="My drop down field"
    ErrorText="*"
    RequiredErrorMessage="This drop down is required"
    CaseSensitiveKeySort="true"
    SelectedValue='<%# Bind("ProductID") %>' />

BoundEntityDropDownField - Như trên nhưng có nguồn gốc từ BoundField để nó có thể sử dụng trong grid (EntityGridView). Nó lưu trữ các dữ liệu để chỉ đọc một lần cho tất cả các hàng bị ràng buộc. 

Ví dụ sử dụng:

<data:EntityGridView runat="server" ID="gridView"
    DataSourceID="productsDataSource"
    DataKeyNames="ProductID" 
    AutoGenerateColumns="false" 
    AutoGenerateEditButton="true" 
    AllowPaging="true" 
    AllowSorting="true">
    <Columns>
        <asp:BoundField DataField="ProductID" HeaderText="Product ID"
            ReadOnly="True"  SortExpression="ProductID" />
        <asp:BoundField DataField="ProductName" HeaderText="Product Name"
            SortExpression="ProductName" />
        <data:BoundEntityDropDownField DataField="SupplierID" HeaderText="Supplier"
            SortExpression="SupplierID" 
            DataSourceID="suppliersDataSource" 
            DataTextField="CompanyName" 
            DataValueField="SupplierID" 
            AppendNullItem="true" />
        <data:BoundEntityDropDownField 
            DataField="CategoryID" 
            HeaderText="Category"
            SortExpression="CategoryID" 
            DataSourceID="categoriesDataSource" 
            DataTextField="CategoryName" 
            DataValueField="CategoryID" 
            AppendNullItem="true" />
    </Columns>
</data:EntityGridView>    
<data:ProductsDataSource runat="server" ID="productsDataSource" sort="ProductName"  
    EnableSorting="true" EnablePaging="true" SelectMethod="GetPaged" />
<data:CategoriesDataSource runat="server" ID="categoriesDataSource" Sort="CategoryName" />
<data:SuppliersDataSource runat="server" ID="suppliersDataSource" Sort="CompanyName" />

Vậy là chúng ta đã xong phần lớp Web Asp.NET. Bài tiếp theo Chúng ta sẽ cùng nghiên cứu WebServices Layer, với lớp này, dữ liệu của bạn sẽ được giữ kín với bên thứ 3. Điều này rất có lợi trong ứng dụng máy chủ. 

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML