数据绑定概述和语法

本文出自:Web程序设计与架构(蔺华 王玉清 电子工业出版社)


1.4  数据绑定基础

1.4.1  数据绑定概述和语法

ASP.NET引入了新的声明性数据绑定语法。这种非常灵活的语法允许开发人员不仅可以绑定到数据源而且可以绑定到简单属性、集合、表达式甚至是从方法调用返回的结果。表1-2显示了新语法的一些示例。

表1-2  ASP.NET引入的新的声明性数据绑定语法

简单属性

Customer: <%# custID %>

集合

Orders: <asp:ListBox id="List1" datasource=

'<%# myArray %>' runat="server">

表达式

Contact: <%# ( customer.First Name + " "

 + customer.LastName ) %>

方法结果

Outstanding Balance: <%# GetBalance(custID) %>

尽管该语法看起来与ASP的Response.Write快捷方式<%= %>相似,但其行为完全不同。ASP Response.Write快捷方式语法在处理页时进行计算,而ASP.NET数据绑定语法仅在调用DataBind方法时计算。

DataBind是页和所有服务器控件的方法。当在父控件上调用DataBind时,它级联到该控件的所有子控件。例如,DataList1.DataBind() 将因此对DataList模板中的每一控件调用DataBind方法。在页上调用DataBind - Page.DataBind() 或只是DataBind() 会导致计算页上的所有数据绑定表达式。通常从Page_Load事件调用DataBind,如下例所示:

protected void Page_Load(Object Src, EventArgs E) {      DataBind();  } 


如果绑定表达式在运行时计算为预期的数据类型,则可以在.aspx页声明节中的几乎任何位置使用绑定表达式。上面的简单属性、表达式和方法示例在计算时向用户显示文本。在这些情况下,数据绑定表达式必须计算为String类型的值。在集合示例中,数据绑定表达式计算ListBox的DataSource属性的有效类型值。你会发现有必要转换绑定表达式中的类型值,以产生所需的结果。例如,如果count是整数:

Number of Records: <%# count.ToString() %> 


 

1.4.2  绑定到简单属性

ASP.NET数据绑定语法支持绑定到公共变量、页的属性和页上其他控件的属性。

下面的示例说明如何绑定到公共变量和页上的简单属性。注意这些值在DataBind() 调用前要初始化。

  1. <html> 
  2. <head> 
  3.  
  4.     <script language="C#" runat="server"> 
  5.  
  6.         void Page_Load(Object sender, EventArgs e) {  
  7.             Page.DataBind();  
  8.         }  
  9.  
  10.         string custID{  
  11.             get {  
  12.                 return "ALFKI";  
  13.             }  
  14.         }  
  15.  
  16.         int orderCount{  
  17.             get {  
  18.                 return 11;  
  19.             }  
  20.         }  
  21.  
  22.  
  23.     </script> 
  24.  
  25. </head> 
  26. <body> 
  27.  
  28.     <h3><font face="宋体">到页属性的数据绑定</font></h3> 
  29.  
  30.     <form runat=server> 
  31.  
  32.         客户:<b><%# custID %></b><br> 
  33.         未结的订单:<b><%# orderCount %></b> 
  34.  
  35.     </form> 
  36.  
  37. </body> 
  38. </html> 

下面的示例说明如何绑定到另一控件的属性。

 
 
  1. <html> 
  2. <head> 
  3.  
  4.     <script language="C#" runat="server"> 
  5.  
  6.         void SubmitBtn_Click(Object sender, EventArgs e) {  
  7.  
  8.           // 仅调用"Page.DataBind",而不是从"StateList"  
  9.           // 中显式取出变量,然后操作标签控件。  
  10.           // 这将计算页内所有的 <%# %> 表达式  
  11.  
  12.           Page.DataBind();  
  13.         }  
  14.  
  15.     </script> 
  16.  
  17. </head> 
  18. <body> 
  19.  
  20.     <h3><font face="宋体">到另一个服务器控件的属性的数据绑定</font></h3> 
  21.  
  22.     <form runat=server> 
  23.  
  24.         <asp:DropDownList id="StateList" runat="server"> 
  25.           <asp:ListItem>CA</asp:ListItem> 
  26.           <asp:ListItem>IN</asp:ListItem> 
  27.           <asp:ListItem>KS</asp:ListItem> 
  28.           <asp:ListItem>MD</asp:ListItem> 
  29.           <asp:ListItem>MI</asp:ListItem> 
  30.           <asp:ListItem>OR</asp:ListItem> 
  31.           <asp:ListItem>TN</asp:ListItem> 
  32.           <asp:ListItem>UT</asp:ListItem> 
  33.         </asp:DropDownList> 
  34.  
  35.         <asp:button Text="提交" OnClick="SubmitBtn_Click" runat=server/> 
  36.  
  37.         <p> 
  38.  
  39.         选定的州:<asp:label text='<%# StateList.SelectedItem.Text %>' runat=server/> 
  40.  
  41.     </form> 
  42.  
  43. </body> 
  44. </html> 

 

1.4.3  绑定到集合和列表

像DataGrid、ListBox和HTMLSelect这样的列表服务器控件将集合用作数据源。下面的示例说明如何绑定到通常的公共语言运行库集合类型。这些控件只能绑定到支持IEnumerable、ICollection或IListSource接口的集合。最常见的是绑定到ArrayList、Hashtable、DataView和DataReader。

绑定到ArrayList的示例如下。

 
 
  1. <html> 
  2. <head> 
  3.     <script language="C#" runat="server"> 
  4.         void Page_Load(Object Sender, EventArgs E) {  
  5.  
  6.             if (!Page.IsPostBack) {  
  7.  
  8.                ArrayList values = new ArrayList();  
  9.  
  10.                values.Add ("IN");  
  11.                values.Add ("KS");  
  12.                values.Add ("MD");  
  13.                values.Add ("MI");  
  14.                values.Add ("OR");  
  15.                values.Add ("TN");  
  16.  
  17.                DropDown1.DataSource = values;  
  18.                DropDown1.DataBind();  
  19.             }  
  20.         }  
  21.         void SubmitBtn_Click(Object sender, EventArgs e) {  
  22.            Label1.Text = "您选择了:" + DropDown1.SelectedItem.Text;  
  23.         }  
  24.  
  25.     </script> 
  26.  
  27. </head> 
  28. <body> 
  29.  
  30.     <h3><font face="宋体">数据绑定 DropDownList</font></h3> 
  31.  
  32.     <form runat=server> 
  33.  
  34.         <asp:DropDownList id="DropDown1" runat="server" /> 
  35.  
  36.         <asp:button Text="提交" OnClick="SubmitBtn_Click" runat=server/> 
  37.  
  38.         <p> 
  39.  
  40.         <asp:Label id=Label1 font-name="宋体" font-size="10.5pt" runat"server" /> 
  41.  
  42.     </form> 
  43.  
  44. </body> 
  45. </html> 

下面的示例说明如何绑定到DataView。注意DataView类在System.Data命名空间中定义。

 
 
  1. <%@ Import namespace="System.Data" %> 
  2.  
  3. <html> 
  4. <head> 
  5.  
  6.     <script language="C#" runat="server"> 
  7.  
  8.         void Page_Load(Object sender, EventArgs e ) {  
  9.  
  10.             if (!Page.IsPostBack) {  
  11.  
  12.                 DataTable dt = new DataTable();  
  13.                 DataRow dr;  
  14.  
  15.                 dt.Columns.Add(new DataColumn("整数值", typeof(Int32)));  
  16.                 dt.Columns.Add(new DataColumn("字符串值", typeof(string)));  
  17.                 dt.Columns.Add(new DataColumn("日期时间值", typeof(Date Time)));  
  18.                 dt.Columns.Add(new DataColumn("布尔值", typeof(bool)));  
  19.  
  20.                 for (int i = 1; i <= 9; i++) {  
  21.  
  22.                     dr = dt.NewRow();  
  23.  
  24.                     dr[0] = i;  
  25.                     dr[1] = "项 " + i.ToString();  
  26.                     dr[2] = DateTime.Now;  
  27.                     dr[3] = (i % 2 != 0) ? true : false;  
  28.  
  29.                     dt.Rows.Add(dr);  
  30.                 }  
  31.  
  32.                 dataGrid1.DataSource = new DataView(dt);  
  33.                 dataGrid1.DataBind();  
  34.             }  
  35.         }  
  36.  
  37.     </script> 
  38.  
  39. </head> 
  40. <body> 
  41.  
  42.     <h3><font face="宋体">到 DataView 的数据绑定</font></h3> 
  43.  
  44.     <form runat=server> 
  45.  
  46.         <asp:DataGrid id="dataGrid1" runat="server" 
  47.           BorderColor="black" 
  48.           BorderWidth="1" 
  49.           GridLines="Both" 
  50.           CellPadding="3" 
  51.           CellSpacing="0" 
  52.           HeaderStyle-BackColor="#aaaadd" 
  53.         /> 
  54.  
  55.     </form> 
  56.  
  57. </body> 
  58. </html> 

 

绑定到Hashtable的示例如下。

 
 
  1. <html> 
  2. <head> 
  3.  
  4.  
  5.     <script language="C#" runat="server"> 
  6.  
  7.         void Page_Load(Object sender, EventArgs e) {  
  8.             if (!Page.IsPostBack) {  
  9.  
  10.                 Hashtable h = new Hashtable();  
  11.                 h.Add ("键 1", "值 1");  
  12.                 h.Add ("键 2", "值 2");  
  13.                 h.Add ("键 3", "值 3");  
  14.  
  15.                 MyDataList.DataSource = h;  
  16.                 MyDataList.DataBind();  
  17.             }  
  18.         }  
  19.  
  20.     </script> 
  21.  
  22. </head> 
  23. <body> 
  24.  
  25.     <h3><font face="宋体">到哈希表的数据绑定</font></h3> 
  26.  
  27.     <form runat=server> 
  28.  
  29.         <asp:DataList id="MyDataList" runat="server" 
  30.           BorderColor="black" 
  31.           BorderWidth="1" 
  32.           GridLines="Both" 
  33.           CellPadding="4" 
  34.           CellSpacing="0" 
  35.           > 
  36.  
  37.             <ItemTemplate> 
  38.                 <%# ((DictionaryEntry)Container.DataItem).Key %> :  
  39.                 <%# ((DictionaryEntry)Container.DataItem).Value %> 
  40.             </ItemTemplate> 
  41.  
  42.         </asp:DataList> 
  43.  
  44.     </form> 
  45.  
  46. </body> 
  47. </html> 

 

1.4.4  绑定到表达式或方法

通常需要在绑定到页或控件之前操作数据。绑定到表达式方法的返回值的示例如下。

 
 
  1. <html> 
  2. <head> 
  3.  
  4.     <script language="C#" runat="server"> 
  5.  
  6.         void Page_Load(Object Src, EventArgs E) {  
  7.  
  8.             if (!Page.IsPostBack) {  
  9.  
  10.                ArrayList values = new ArrayList();  
  11.  
  12.                values.Add (0);  
  13.                values.Add (1);  
  14.                values.Add (2);  
  15.                values.Add (3);  
  16.                values.Add (4);  
  17.                values.Add (5);  
  18.                values.Add (6);  
  19.  
  20.                DataList1.DataSource = values;  
  21.                DataList1.DataBind();  
  22.             }  
  23.         }  
  24.  
  25.         String EvenOrOdd(int number) {  
  26.             if ((number % 2) == 0)  
  27.               return "偶数";  
  28.             else  
  29.               return "奇数";  
  30.         }  
  31.  
  32.     </script> 
  33.  
  34. </head> 
  35. <body> 
  36.  
  37.     <h3><font face="宋体">到方法和表达式的数据绑定</font></h3> 
  38.  
  39.     <form runat=server> 
  40.  
  41.       <asp:DataList id="DataList1" runat="server" 
  42.         BorderColor="black" 
  43.         BorderWidth="1" 
  44.         GridLines="Both" 
  45.         CellPadding="3" 
  46.         CellSpacing="0" 
  47.         > 
  48.  
  49.         <ItemTemplate> 
  50.           数字值:<%# Container.DataItem %> 
  51.           偶/奇:<%# EvenOrOdd((int) Container.DataItem) %> 
  52.         </ItemTemplate> 
  53.  
  54.       </asp:datalist> 
  55.  
  56.     </form> 
  57.  
  58. </body> 
  59. </html> 

 

1.4.5  DataBinder.Eval()

ASP.NET框架提供了一种静态方法,计算后期绑定的数据绑定表达式,并且可选择将结果格式化为字符串。DataBinder.Eval很方便,因为它消除了开发人员为强迫将值转换为所需的数据类型而必须做的许多显式转换。这在数据绑定模板列表内的控件时尤其有用,因为通常数据行和数据字段的类型都必须转换。

请看下面的示例,本例中整数将显示为货币字符串。使用标准的ASP.NET数据绑定语法,必须首先转换数据行的类型,以便检索数据字段IntegerValue。下一步,将此作为参数传递给String.Format方法。

 
 
  1. <%# String.Format("{0:c}", ((DataRowView)Container.DataItem)["IntegerValue"]) %> 

该语法比较复杂,难以记忆。相反,DataBinder.Eval只是一个具有三个参数的方法:数据项的命名容器、数据字段名和格式字符串。在像DataList、DataGrid或Repeater这样的模板列表中,命名容器始终是Container.DataItem。Page是另一个可与DataBinder.Eval一起使用的命名容器。

 
 
  1. <%# DataBinder.Eval(Container.DataItem, "IntegerValue", "{0:c}") %> 

格式字符串参数是可选的。如果省略它,则DataBinder.Eval返回对象类型的值,如以下示例所示。

 
 
  1. <%# (bool)DataBinder.Eval(Container.DataItem, "BoolValue") %> 

DataBinder.Eval会对标准数据绑定语法带来很明显的性能损失,因为它使用后期绑定反射,注意这一点很重要。使用DataBinder.Eval时需要谨慎,尤其是在不需要字符串格式化时。

 
 
  1. <%@ Import namespace="System.Data" %> 
  2.  
  3. <html> 
  4. <head> 
  5.  
  6.  
  7.     <script language="C#" runat="server"> 
  8.  
  9.         void Page_Load(Object sender, EventArgs e) {  
  10.  
  11.             if (!Page.IsPostBack) {  
  12.  
  13.                 DataTable dt = new DataTable();  
  14.                 DataRow dr;  
  15.  
  16.                 dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));  
  17.                 dt.Columns.Add(new DataColumn("StringValue", typeof(string)));  
  18.                 dt.Columns.Add(new DataColumn("DateTimeValue", typeof(Date Time)));  
  19.                 dt.Columns.Add(new DataColumn("BoolValue", typeof(bool)));  
  20.  
  21.                 for (int i = 0; i < 9; i++) {  
  22.  
  23.                     dr = dt.NewRow();  
  24.  
  25.                     dr[0] = i;  
  26.                     dr[1] = "项 " + i.ToString();  
  27.                     dr[2] = DateTime.Now;  
  28.                     dr[3] = (i % 2 != 0) ? true : false;  
  29.  
  30.                     dt.Rows.Add(dr);  
  31.                 }  
  32.  
  33.                 dataList1.DataSource = new DataView(dt);  
  34.                 dataList1.DataBind();  
  35.             }  
  36.         }  
  37.  
  38.     </script> 
  39.  
  40. </head> 
  41. <body> 
  42.  
  43.     <h3><font face="宋体">使用 DataBinder.Eval 进行数据绑定</font></h3> 
  44.  
  45.     <form runat=server> 
  46.  
  47.         <asp:DataList id="dataList1" runat="server" 
  48.           RepeatColumns="3" 
  49.           Width="80%" 
  50.           BorderColor="black" 
  51.           BorderWidth="1" 
  52.           GridLines="Both" 
  53.           CellPadding="4" 
  54.           CellSpacing="0" 
  55.           > 
  56.  
  57.             <ItemTemplate> 
  58.  
  59.                 订购日期:<%# DataBinder.Eval(Container.DataItem, "DateTime Value", "{0:d}") %> 
  60.  
  61.                 <p> 
  62.  
  63.                 数量:<%# DataBinder.Eval(Container.DataItem,  "IntegerValue", "{0:N2}") %> 
  64.  
  65.                 <p> 
  66.  
  67.                 项:<%# DataBinder.Eval(Container.DataItem, "StringValue") %> 
  68.  
  69.                 订购日期: <asp:CheckBox id=chk1 Checked='<%#  (bool)DataBinder. Eval (Container.DataItem, "BoolValue") %>' runat=server/> 
  70.  
  71.                 <p> 
  72.  
  73.             </ItemTemplate> 
  74.  
  75.         </asp:Datalist> 
  76.  
  77.     </form> 
  78.  
  79. </body> 
  80. </html> 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值