The sample Login.aspx
ASP.NET file shows one of the best reasons why we use NHibernate. By using an ObjectDataSource, we can map the NHibernate objects directly to the data-bound controls that will display or interact with them. All we have to do is create an ObjectDataSource to retrieve the data from our data access class (LoginDataControl.cs
), create a set of form fields to display the data (like the <asp:GridView>
"LoginGrid" below), and let ASP.NET handle all of the tedious work for us. By the way, this page will work exactly as shown—there is no page logic in the code behind or anywhere else.
All we have in this code is a GridView to present the information and an ObjectDataSource to interact with our DataAccess classes and provide data for the GridView. The GridView has BoundField definitions for all of the fields in our database table as well as Sorting and Paging functions. The ObjectDataSource has methods mapped for Select
, Select
Count
, Insert
, and Update
. When the GridView needs to perform one of these functions, it relies on the ObjectDataSource to handle these operations. Working in tandem, these two controls (as well as nearly any other data bound control) can provide a very quick and simple interface for your data!
<%@ Page Language="C#" AutoEventWireup="true"CodeBehind="Default.aspx.cs" Inherits="BasicWebApplication.Web._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <asp:GridView ID="LoginGrid" AutoGenerateColumns="false" DataSourceID="LoginSource" runat="server"> <Columns> <asp:HyperLinkField HeaderText="ID" DataTextField="Id" SortExpression="Id" DataNavigateUrlFields="Id"DataNavigateUrlFormatString="~/SampleForms/Login.aspx?LoginId={0}"Target="_parent" /> <asp:BoundField HeaderText="FirstName" DataField="FirstName" /> <asp:BoundField HeaderText="LastName" DataField="LastName" /> <asp:BoundField HeaderText="UserName" DataField="UserName" /> <asp:BoundField HeaderText="Password" DataField="Password" /> </Columns> </asp:GridView> <asp:ObjectDataSource ID="LoginSource" TypeName="BasicWebApplication.DataAccess.LoginDataControl"DataObjectTypeName="BasicWebApplication.Common.DataObjects.Login" SelectMethod="GetAll" SelectCountMethod="GetCountOfAll" runat="server"></asp:ObjectDataSource> </form> </body> </html>