ASP.NET2.0+SQL Server2005构建多层应用(4)
2006-01-10 16:41:06 来源:CSDN 作者: 点击:
</asp:objectdatasource>
<asp:gridview runat="server" AutoGenerateColumns="false" id="authorsView" datasourceid="authorsSource">
<alternatingrowstyle backcolor="Silver"></alternatingrowstyle>
<Columns>
<asp:HyperLinkField DataTextField="au_id" HeaderText="Author ID" DataNavigateUrlFields="au_id"
DataNavigateUrlFormatString="AuthorTitles.aspx?AuthorID={0}">
</asp:HyperLinkField>
<asp:BoundField HeaderText="Last Name" DataField="au_lname"></asp:BoundField>
<asp:BoundField HeaderText="First Name" DataField="au_fname"></asp:BoundField>
<asp:BoundField HeaderText="Phone" DataField="phone"></asp:BoundField>
<asp:BoundField HeaderText="Address" DataField="address"></asp:BoundField>
<asp:BoundField HeaderText="City" DataField="city"></asp:BoundField>
<asp:BoundField HeaderText="State" DataField="state"></asp:BoundField>
<asp:BoundField HeaderText="Zip" DataField="zip"></asp:BoundField>
</Columns>
</asp:gridview>
</asp:content>
注意,其中我们用到了objectdatasource控件,在.NET 2.0中,有了该控件,可以很方便地沟通表示层和逻辑层。其中的代码如下:
<asp:objectdatasource runat="server" id="authorsSource" typename="AuthorsBiz" selectmethod="GetAuthors">
</asp:objectdatasource>
其中的typename属性指定为我们之前创建的逻辑层的类AuthorsBiz类,而为了获得数据,采用了selectmethod方法,这里指定了之前建立的GetAuthors方法。当然,也可以在其他场合,应用Updatemethod,Insertmethod,Deletemethod方法,也可以加上参数,比如接下来要创建的AuthorTitle.aspx页面,代码如下:
<%@ Page Language="C#" MasterPageFile="~/CommonMaster.master" %>
<asp:content id="Content1" contentplaceholderid="middleContent" runat="server">
<asp:objectdatasource runat="server" id="authorTitlesSource" typename="AuthorsBiz" selectmethod="GetAuthorTitles">
<SelectParameters>
<asp:QueryStringParameter Type="String" Direction="Input" Name="authorID" QueryStringField="AuthorID" />
</SelectParameters>
</asp:objectdatasource>
<asp:gridview runat="server" id="authorTitlesView" datasourceid="authorTitlesSource">
<alternatingrowstyle backcolor="Silver"></alternatingrowstyle>
</asp:gridview>
</asp:content>
上面的代码中,首先用户在authors.aspx页面点选某个作者名时,则在authortitle.aspx页面中,返回该作者的所有著作。所以,在objectdatasource控件中,我们使用了SelectParameters参数,指定传入来要查询的参数是authorid。最后,再将gridview绑定到objectdatasource控件中去。
最后,运行我们的代码,结果如下两图所表示:
小结 在ASP.NET 2.0中,我们利用SQL Server 2005的强大功能,可以利用.NET 语言创建存储过程,并使用TableAdapter向导,很方便地创建数据访问层,再利用objectdatasource控件的特性,可以很方便地沟通表示层和逻辑层。