ASP.NET 2.0 数据绑定高级技巧
介绍更高级的数据绑定技巧,不但把数据绑定在表示层,更通过使用架构的方法,来实现跨层数据绑定。
本文中涉及的代码皆不能单独运行,仅供作代码示例;建议下载本文提供的相关附件阅读更为详细!
ASP.NET 2.0数据绑定高级技巧内容概述
简单数据绑定
数据源控件
数据控件 GridView 与DetailsView 控件
缓存 配置缓存 Cache configuration
简单数据绑定
数据绑定变的更简单,并支持XML数据源定
<%# DataBinder.Eval(Container.DataItem, "Price") %>
<%# Eval("Price") %>
<%# XPath("Price") %>
数据源控件
无代码的数据绑定
控件名 控件描述
SqlDataSource 一切支持SQL语句的数据源控件
AccessDataSource Access数据源控件
XmlDataSource XML数据源控件
ObjectDataSource 自行编写组件的数据源控件
SiteMapDataSource 页面导航控件的数据源控件
SqlDataSource
支持数据绑定到SQL 数据库
任何支持SQL语句的数据库都在支持之列
两种数据绑定方式
SelectCommand 定义查询操作,InsertCommand, UpdateCommand, and DeleteCommand 定义更新操作
可以对查询结果使用缓存
可以对参加添加参数
使用SqlDataSource
ConnectionString="server=localhost;database=pubs;integratedsecurity=true"
SelectCommand="select title_id, title, price from titles" />
SqlDataSource 关键属性
名称 描述
ConnectionString 连接数据库的连接字符串
SelectCommand 用于执行查询的命令
InsertCommand 用于执行插入的命令
UpdateCommand 用于执行更新的命令
DeleteCommand 用于执行删除的命令
DataSourceMode 指定数据源类型是DataSet 或DataReader( 默认值= DataSet)
ProviderName 指定供应商(默认值= SQL Server .NET provider)
SqlDataSource 与缓存
SqlDataSource 支持通过以下属性进行数据
缓存:
属性 描述
EnableCaching 指定是否打开缓存(默认值= false)
CacheDuration 指定结果被缓存多少妙
CacheExpirationPolicy 指定缓存间隔是sliding 还是absolute
CacheKeyDependency 使缓存依赖于一个特定键值
SqlCacheDependency 使缓存依赖于一个特定数据库实体
缓存查询结果
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select distinct country from customers order by country"
EnableCaching="true" CacheDuration="60" />
DataTextField="country" AutoPostBack="true" RunAt="server" />
参数化命令
参数属性允许数据库命令带参数执行
例如:通过下来框获得查询语句的参数
例如:从GridView控件中获得删除命令的参数
XxxParameter 类型指定参数来源
XxxParameters 属性
名称 描述
SelectParameters 为查询命令指定参数
InsertParameters 为插入命令指定参数
UpdateParameters 为更新命令指定参数
DeleteParameters 为删除命令指定参数
FilterParameters 为过滤器命令指定参数
Parameter 为数据源绑定一个参数
ControlParameter 指定一个源自于控件的参数
CookieParameter 指定一个源自于cookie 的参数
FormParameter 指定一个源自于表单的参数
ProfileParameter 指定一个源自于profile的参数
QueryStringParameter 制定于一个来源于查询字符串的参数
SessionParameter 指定一个源自于session 的参数
使用ControlParameter
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select distinct country from customers order by country" />
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select * from customers where country=@Country">
PropertyName="SelectedValue" />
调用存储过程
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="proc_GetCountries" />
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="proc_GetCustomers">
PropertyName="SelectedValue" />
DataTextField="country" AutoPostBack="true" RunAt="server" />
Create PROCEDURE proc_GetCustomers
@Country nvarchar(32) AS
Select * FROM Customers
Where Country = @Country
GO
Create PROCEDURE proc_GetCountries As
Select DISTINCT Country FROM Customers
orDER BY Country
GO
SqlDataSource
XmlDataSource
使用XML 作为数据源
支持缓存与XSL 转换
只支持查询绑定,不支持更新
XmlDataSource 的关键属性
名称 描述
DataFile XML 数据文件的路径
TransformFile 含有XSL 风格定义的数据文件路径
EnableCaching 指定是否开启cache (默认值= false)
CacheDuration 以秒为单位的时间间隔
CacheExpirationPolicy 指定时间间隔是sliding 还是absolute
CacheKeyDependency 创建缓存依存于某个键
Xpath Xpath 表达式用来确认数据
ObjectDataSource
从数据组件绑定数据
提供中间件的数据绑定
使数据访问和UI脱离
两种数据绑定方式
SelectMethod, InsertMethod, UpdateMethod,and DeleteMethod
可选择是否使用缓存
可选择是否使用参数
ODS 关键属性
名称 描述
TypeName 数据组件的类型名称
SelectMethod 调用查询方法
InsertMethod 调用插入方法
UpdateMethod 调用更新方法
DeleteMethod 调用删除方法
EnableCaching 指定是否缓存(默认值= false)
CacheDuration 缓存间隔时间以秒为单位
SqlCacheDependency 基于某个数据实体的缓存
SelectParameters 指定查询方法参数
InsertParameters 指定插入方法参数
UpdateParameters 指定更新方法参数
DeleteParameters 指定删除方法参数
创建和清除 ObjectDataSource
ObjectDataSource.SelectMethod 可以使用静
态方法也可以使用一个类的新实例
如果使用实例方法:
ODS 在每次调用的时候创建一个新实例
类必须具有公共的建构函数
使用ObjectCreated 和ObjectDisposing 元素
可以初始化和撤销函数
GridView 控件
增强的DataGrid 控件
使用HTML 表格来显示数据
内置支持排序, 分页, 查询, 更新, 以及删除操
作
支持复杂的数据单元格类型,包括
CheckBoxFields
元素中声明
高可定制的用户界面
GridView 示例
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select lastname, firstname, title from employees" />
GridView 输出
GridView 列类型
名称 描述
BoundField 显示数据库中取出的文本
ButtonField 显示按钮
CheckBoxField 使用check boxes显示一个boolean型变量
CommandField 显示一个查询或者编辑按钮
HyperLinkField 显示一个超链接
ImageField 显示一个图片
TemplateField 显示一个自定义的HTML模板
指定区域类型
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select photo, lastname, firstname, title from employees" />
AutoGenerateColumns="false" >
<%# Eval("firstname") + " " + Eval("lastname") %>
DetailsView 控件
显示个别的记录
配合GridView 显示master-detail 视图
显示一个单独的记录
内建了分页,查询,添加,删除操作
使用与GridView完全相同的单元格类型
在 元素中声明
Highly customizable UI
DetailsView 示例
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select employeeid, photo, … from employees" />
AllowPaging="true" AutoGenerateRows="false"
PagerSettings-Mode="NextPreviousFirstLast">
<%# Eval("firstname") + " " + Eval("lastname") %>
DetailsView插入, 更新, 和删除
数据显示控件支持从用户界面进行编辑
AutoGenerateXxxButton 属性
Insert/EditRowStyle 属性
数据源控件支持编辑逻辑
Insert/Update/DeleteCommand 属性
Insert/Update/DeleteParameters 属性
Inserting/ed, Updating/ed, Deleting/ed 事件
Visual Studio 支持两者的结合
使用GridViews进行数据编辑
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select employeeid, lastname, firstnamefrom employees"
UpdateCommand="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid">
DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />
冲突判定
先入胜利
如果数据在取出之后被改变,则修改失败
UpdateCommand 结构构成
指定ConflictDetection=“CompareAllValues”来实现
后入胜利
无论数据是否被修改,该修改都会成功
UpdateCommand 结构构成
指定ConflictDetection=“OverwriteChanges”来实现
先入胜利法则更新
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select employeeid, lastname, firstnamefrom employees"
UpdateCommand="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid and lastname=
@original_lastnameand firstname=@original_firstname"
ConflictDetection="CompareAllValues">
DataKeyNames="EmployeeID" AutoGenerateEditButton="true" />
错误检测
数据更新后控件调用的事件
GridView.RowUpdated
DetailsView.ItemUpdated
SqlDataSource.Updated, etc.
处理“status”的事件
无论数据库是否异常,允许数据库异常被处理或者再次抛弃, 显示多少数据库行被修改
处理更新错误
UpdateCommand="…" OnUpdated="OnUpdateComplete">
…
…
void OnUpdateComplete (Object source, SqlDataSourceStatusEventsArgse)
{
if (e.Exception!= null) {
// Exception thrown. Set e.ExceptionHandledto true to prevent
// the SqlDataSourcefrom throwing an exception, or leave it set
// to false to allow SqlDataSourceto rethrowthe exception
}
else if (e.AffectedRows== 0) {
// No exception was thrown, but no records were updated,either.
// Might want to let the user know that the update failed
}
}
使用GridViews 和DetailsViews编辑数据
DataSet的性能
Dataset能支持真正意义上的Binary序列化了, 而我们需要做的工作呢,只用写一句话:
ds.RemotingFormat=SerializationFormat.Binary
对一个包含3个column, 大约10000条数据的Dataset, 采用binary序列化生成的文件大小是采用xml序列化的28% (457kb : 1.6MB), 花费的时间只是xml 的35 %. 看上去真好极了.
SQL 缓存
新的缓存依赖属性类型
包含于SqlCacheDependency 类,通过 来配置
连接数据库实体
ASP.NET 应用缓存
ASP.NET 输出缓存
兼容SQL Server 7, 2000, 2005
数据库准备
使用Aspnet_regsql.exe 或者SqlCache-DependencyAdmin 做好数据库准备*
aspnet_regsql-S localhost-E -d Northwind-ed
相关参数: 服务器名称 连接方式,这里使用致信连接 数据库名称 表名称 启用表监视
使用Aspnet_regsql.exeor SqlCache-DependencyAdmin 准备数据表*
aspnet_regsql-S localhost-E -d Northwind-t Products -e t
相关参数: 服务器名称 可信任的连接 数据库名称 表名称 启用表监视
* SQL Server 2005不需要配置
准备Web.config
connectionString="server=localhost;database=northwind;…" />
使用系统缓存
Cache.Insert("Products", products,
new SqlCacheDependency("Northwind", "Products");
使用输出缓存
<%@ OutputCacheDuration="60" VaryByParam="None"
SqlDependency="Northwind:Products" %>
对SqlDataSource使用缓存
ConnectionString="server=localhost;database=northwind;…"
SelectCommand="select distinct country from customers order by country"
EnableCaching="true" CacheDuration="60000"
SqlCacheDependency="Northwind:Customers" />
DataTextField="country" AutoPostBack="true" RunAt="server" />
缓存配置
Enable/disable 应用缓存
Enable/disable 元素是否到期
,
Enable/disable 显示缓存
Enable/disable 基于磁盘的缓存
为每个应用程序指定最大的缓存空间
GridView 与DetailsView 控件结合使用
介绍更高级的数据绑定技巧,不但把数据绑定在表示层,更通过使用架构的方法,来实现跨层数据绑定。
本文中涉及的代码皆不能单独运行,仅供作代码示例;建议下载本文提供的相关附件阅读更为详细!
ASP.NET 2.0数据绑定高级技巧内容概述
简单数据绑定
数据源控件
数据控件 GridView 与DetailsView 控件
缓存 配置缓存 Cache configuration
简单数据绑定
数据绑定变的更简单,并支持XML数据源定
<%# DataBinder.Eval(Container.DataItem, "Price") %>
<%# Eval("Price") %>
<%# XPath("Price") %>
数据源控件
无代码的数据绑定
控件名 控件描述
SqlDataSource 一切支持SQL语句的数据源控件
AccessDataSource Access数据源控件
XmlDataSource XML数据源控件
ObjectDataSource 自行编写组件的数据源控件
SiteMapDataSource 页面导航控件的数据源控件
SqlDataSource
支持数据绑定到SQL 数据库
任何支持SQL语句的数据库都在支持之列
两种数据绑定方式
SelectCommand 定义查询操作,InsertCommand, UpdateCommand, and DeleteCommand 定义更新操作
可以对查询结果使用缓存
可以对参加添加参数
使用SqlDataSource
SelectCommand="select title_id, title, price from titles" />
SqlDataSource 关键属性
名称 描述
ConnectionString 连接数据库的连接字符串
SelectCommand 用于执行查询的命令
InsertCommand 用于执行插入的命令
UpdateCommand 用于执行更新的命令
DeleteCommand 用于执行删除的命令
DataSourceMode 指定数据源类型是DataSet 或DataReader( 默认值= DataSet)
ProviderName 指定供应商(默认值= SQL Server .NET provider)
SqlDataSource 与缓存
SqlDataSource 支持通过以下属性进行数据
缓存:
属性 描述
EnableCaching 指定是否打开缓存(默认值= false)
CacheDuration 指定结果被缓存多少妙
CacheExpirationPolicy 指定缓存间隔是sliding 还是absolute
CacheKeyDependency 使缓存依赖于一个特定键值
SqlCacheDependency 使缓存依赖于一个特定数据库实体
缓存查询结果
SelectCommand="select distinct country from customers order by country"
EnableCaching="true" CacheDuration="60" />
参数化命令
参数属性允许数据库命令带参数执行
例如:通过下来框获得查询语句的参数
例如:从GridView控件中获得删除命令的参数
XxxParameter 类型指定参数来源
XxxParameters 属性
名称 描述
SelectParameters 为查询命令指定参数
InsertParameters 为插入命令指定参数
UpdateParameters 为更新命令指定参数
DeleteParameters 为删除命令指定参数
FilterParameters 为过滤器命令指定参数
Parameter 为数据源绑定一个参数
ControlParameter 指定一个源自于控件的参数
CookieParameter 指定一个源自于cookie 的参数
FormParameter 指定一个源自于表单的参数
ProfileParameter 指定一个源自于profile的参数
QueryStringParameter 制定于一个来源于查询字符串的参数
SessionParameter 指定一个源自于session 的参数
使用ControlParameter
SelectCommand="select distinct country from customers order by country" />
SelectCommand="select * from customers where country=@Country">
调用存储过程
SelectCommand="proc_GetCountries" />
SelectCommand="proc_GetCustomers">
Create PROCEDURE proc_GetCustomers
@Country nvarchar(32) AS
Select * FROM Customers
Where Country = @Country
GO
Create PROCEDURE proc_GetCountries As
Select DISTINCT Country FROM Customers
orDER BY Country
GO
SqlDataSource
XmlDataSource
使用XML 作为数据源
支持缓存与XSL 转换
只支持查询绑定,不支持更新
XmlDataSource 的关键属性
名称 描述
DataFile XML 数据文件的路径
TransformFile 含有XSL 风格定义的数据文件路径
EnableCaching 指定是否开启cache (默认值= false)
CacheDuration 以秒为单位的时间间隔
CacheExpirationPolicy 指定时间间隔是sliding 还是absolute
CacheKeyDependency 创建缓存依存于某个键
Xpath Xpath 表达式用来确认数据
ObjectDataSource
从数据组件绑定数据
提供中间件的数据绑定
使数据访问和UI脱离
两种数据绑定方式
SelectMethod, InsertMethod, UpdateMethod,and DeleteMethod
可选择是否使用缓存
可选择是否使用参数
ODS 关键属性
名称 描述
TypeName 数据组件的类型名称
SelectMethod 调用查询方法
InsertMethod 调用插入方法
UpdateMethod 调用更新方法
DeleteMethod 调用删除方法
EnableCaching 指定是否缓存(默认值= false)
CacheDuration 缓存间隔时间以秒为单位
SqlCacheDependency 基于某个数据实体的缓存
SelectParameters 指定查询方法参数
InsertParameters 指定插入方法参数
UpdateParameters 指定更新方法参数
DeleteParameters 指定删除方法参数
创建和清除 ObjectDataSource
ObjectDataSource.SelectMethod 可以使用静
态方法也可以使用一个类的新实例
如果使用实例方法:
ODS 在每次调用的时候创建一个新实例
类必须具有公共的建构函数
使用ObjectCreated 和ObjectDisposing 元素
可以初始化和撤销函数
GridView 控件
增强的DataGrid 控件
使用HTML 表格来显示数据
内置支持排序, 分页, 查询, 更新, 以及删除操
作
支持复杂的数据单元格类型,包括
CheckBoxFields
高可定制的用户界面
GridView 示例
SelectCommand="select lastname, firstname, title from employees" />
GridView 输出
GridView 列类型
名称 描述
BoundField 显示数据库中取出的文本
ButtonField 显示按钮
CheckBoxField 使用check boxes显示一个boolean型变量
CommandField 显示一个查询或者编辑按钮
HyperLinkField 显示一个超链接
ImageField 显示一个图片
TemplateField 显示一个自定义的HTML模板
指定区域类型
SelectCommand="select photo, lastname, firstname, title from employees" />
<%# Eval("firstname") + " " + Eval("lastname") %>
DetailsView 控件
显示个别的记录
配合GridView 显示master-detail 视图
显示一个单独的记录
内建了分页,查询,添加,删除操作
使用与GridView完全相同的单元格类型
在
Highly customizable UI
DetailsView 示例
SelectCommand="select employeeid, photo, … from employees" />
PagerSettings-Mode="NextPreviousFirstLast">
<%# Eval("firstname") + " " + Eval("lastname") %>
DetailsView插入, 更新, 和删除
数据显示控件支持从用户界面进行编辑
AutoGenerateXxxButton 属性
Insert/EditRowStyle 属性
数据源控件支持编辑逻辑
Insert/Update/DeleteCommand 属性
Insert/Update/DeleteParameters 属性
Inserting/ed, Updating/ed, Deleting/ed 事件
Visual Studio 支持两者的结合
使用GridViews进行数据编辑
SelectCommand="select employeeid, lastname, firstnamefrom employees"
UpdateCommand="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid">
冲突判定
先入胜利
如果数据在取出之后被改变,则修改失败
UpdateCommand 结构构成
指定ConflictDetection=“CompareAllValues”来实现
后入胜利
无论数据是否被修改,该修改都会成功
UpdateCommand 结构构成
指定ConflictDetection=“OverwriteChanges”来实现
先入胜利法则更新
SelectCommand="select employeeid, lastname, firstnamefrom employees"
UpdateCommand="update employees set lastname=@lastname, firstname=
@firstnamewhere employeeid=@original_employeeid and lastname=
@original_lastnameand firstname=@original_firstname"
ConflictDetection="CompareAllValues">
错误检测
数据更新后控件调用的事件
GridView.RowUpdated
DetailsView.ItemUpdated
SqlDataSource.Updated, etc.
处理“status”的事件
无论数据库是否异常,允许数据库异常被处理或者再次抛弃, 显示多少数据库行被修改
处理更新错误
…
…
void OnUpdateComplete (Object source, SqlDataSourceStatusEventsArgse)
{
if (e.Exception!= null) {
// Exception thrown. Set e.ExceptionHandledto true to prevent
// the SqlDataSourcefrom throwing an exception, or leave it set
// to false to allow SqlDataSourceto rethrowthe exception
}
else if (e.AffectedRows== 0) {
// No exception was thrown, but no records were updated,either.
// Might want to let the user know that the update failed
}
}
使用GridViews 和DetailsViews编辑数据
DataSet的性能
Dataset能支持真正意义上的Binary序列化了, 而我们需要做的工作呢,只用写一句话:
ds.RemotingFormat=SerializationFormat.Binary
对一个包含3个column, 大约10000条数据的Dataset, 采用binary序列化生成的文件大小是采用xml序列化的28% (457kb : 1.6MB), 花费的时间只是xml 的35 %. 看上去真好极了.
SQL 缓存
新的缓存依赖属性类型
包含于SqlCacheDependency 类,通过
连接数据库实体
ASP.NET 应用缓存
ASP.NET 输出缓存
兼容SQL Server 7, 2000, 2005
数据库准备
使用Aspnet_regsql.exe 或者SqlCache-DependencyAdmin 做好数据库准备*
aspnet_regsql-S localhost-E -d Northwind-ed
相关参数: 服务器名称 连接方式,这里使用致信连接 数据库名称 表名称 启用表监视
使用Aspnet_regsql.exeor SqlCache-DependencyAdmin 准备数据表*
aspnet_regsql-S localhost-E -d Northwind-t Products -e t
相关参数: 服务器名称 可信任的连接 数据库名称 表名称 启用表监视
* SQL Server 2005不需要配置
准备Web.config
使用系统缓存
Cache.Insert("Products", products,
new SqlCacheDependency("Northwind", "Products");
使用输出缓存
<%@ OutputCacheDuration="60" VaryByParam="None"
SqlDependency="Northwind:Products" %>
对SqlDataSource使用缓存
SelectCommand="select distinct country from customers order by country"
EnableCaching="true" CacheDuration="60000"
SqlCacheDependency="Northwind:Customers" />
缓存配置
Enable/disable 应用缓存
Enable/disable 元素是否到期
Enable/disable 显示缓存
Enable/disable 基于磁盘的缓存
为每个应用程序指定最大的缓存空间
GridView 与DetailsView 控件结合使用
浙公网安备 33010602011771号