2.创建连接到数据库的DataService
下面,我们先列出这个DataService相关的MyDataService.asmx的关键代码:
列表7
|
//……(省略) using System.ComponentModel; using System.Web.Services; using System.Web.Services.Protocols; using System.Data; using System.Web.Script.Services; using Microsoft.Web.Preview.Services; using Demos.Employee;//defines class SqlTaskProvider [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] public class MyDataService : DataService { [WebMethod] [DataObjectMethod(DataObjectMethodType.Delete)] public void DeleteRecord(Employee emp) { if (emp.Name == null) { throw new AccessViolationException(); } new SqlTaskProvider().DeleteRecord(emp); } [WebMethod] [DataObjectMethod(DataObjectMethodType.Select)] public List<Employee> GetAllRecords() { return new SqlTaskProvider().GetAllRecords(); } [WebMethod] [DataObjectMethod(DataObjectMethodType.Insert)] public void InsertRecord(Employee emp) { if (emp.Name == null) { throw new AccessViolationException(); } new SqlTaskProvider().InsertRecord(emp); } [WebMethod] [DataObjectMethod(DataObjectMethodType.Update)] public void UpdateRecord(Employee emp) { if (emp.Name == null) { throw new AccessViolationException(); } new SqlTaskProvider().UpdateRecord(emp); } } |
略微加以分析,你应该得如图5所示的调用关系图:
![]() |
| 图5:例2中各主要模块间的调用关系 |
接下来,让我们分析数据绑定是如何在客户端实现的。注意,这里我们仍然使用xml-script声明性方式。
4.客户端声明性编程
在此,非常类似于前一个例子,我们首先建立HTML元素与控件ItemView的模板间的映射关系:
列表8
广州网站建设,网站建设,广州网页设计,广州网站设计
|
<script type="text/xml-script"> <page xmlns:script="http://schemas.microsoft.com/xml-script/2005"> <components> <dataSource id="EmployeeDataSource" serviceURL="MyDataService.asmx" > </dataSource> <itemView id="detailsView"> <bindings> <binding dataContext="EmployeeDataSource" dataPath="data" property="data" /> <binding dataContext="EmployeeDataSource" dataPath="isReady" property="element" propertyKey="enabled"/> </bindings> <itemTemplate> <template layoutElement="detailsTemplate"> <textBox id="nameField"> <bindings> <binding dataPath="Name" property="text" direction="InOut"/> </bindings> </textBox> <textBox id="addressField"> <bindings> <binding dataPath="Address" property="text" direction="InOut"/> </bindings> </textBox> </template> </itemTemplate> <emptyTemplate> <template layoutElement="emptyTemplate" /> </emptyTemplate> </itemView> |
在此,有几处需要注意。首先,控件ItemView典型地用于显示一条记录—基于MS AJAX客户端数据绑定方案,而控件ListView却用于显示满足一定范围的一批记录。其次,控件ItemView使用了两个绑定:第一个绑定将把从DataSource返回的数据绑定到控件ItemView的data属性上,以确保ItemView控件能够从数据源取得它所要求的完整的数据;第二个绑定把ItemView控件的enabled属性绑定到DataSource的IsReady属性上。这意味着,当数据源还没有准备好时(例如数据源正在从服务器端读写数据),控件ItemView将被禁用。第三,我们使用了双向绑定技术,这意味着不仅源控件属性(dataContext属性指向的那个)的改变将更新目标控件相应的属性,而且反过来也如此。最后,我们还要注意,DataSource的改变将使数据变‘脏’—DataSource控件的isDirty属性将被置为true。




