Digging Into Data Binding Expressions

本文深入探讨ASP.NET数据绑定表达式,介绍其常见场景,如在Repeater和DataGrid中的应用。还展示了可绑定自定义对象集合,以及利用数据绑定改变控件外观。分析了运行时数据绑定原理,对比了Eval和强制类型转换的优劣,并介绍从数据绑定表达式调用代码隐藏类方法的技巧。
 

Data binding expressions in ASP.NET are the small snippets of code you see between <%# and %> characters in an ASPX file. We normally see these expressions in a Repeater’s ItemTemplate declarations, and in a DataGrid's  TemplateColumn markup. Also, Data binding expressions often contain a call to the DataBinder.Eval method. Although these are the common scenarios for data binding in ASP.NET, there is more you can do with a little knowledge of what happens underneath the covers. In this article we will take a look at how the data binding expressions work, where they work, and demonstrate some additional tricks you can use to get more from your data binding expressions.

As a refresher, let’s look at a simple webform with data binding expressions:

<form id="Form1" method="post" runat="server">
  <table>         
    <asp:Repeater id="Repeater1" runat="server">
      <ItemTemplate>
        <tr>
          <td><%# DataBinder.Eval(Container.DataItem, "Name") %></td>
          <td><%# DataBinder.Eval(Container.DataItem, "HexValue") %></td>
        </tr>
      </ItemTemplate>
    </asp:Repeater>
  </table>
</form>

This produces the web form shown below.

In this example we have a Repeater control displaying color names and their hexadecimal equivalents. We know we can bind a Repeater to DataTable objects, DataView objects, SqlDataReader objects, and others. One of the nice features of data binding is how ASP.NET abstracts away the ultimate source of the data and we don’t need to know the exact type of the object we are binding against.

Our first data binding tip is that you can also bind against a collection of custom objects. For instance, in our sample web form we are using an ArrayList of Color classes, where the Color class is our own custom class, defined below.

public class Color
{
   public Color(string name, byte r, byte g, byte b)
   {
      this.name = name;
      hexValue = String.Format(
                        "#{0:X2}{1:X2}{2:X2}",
                        r, g, b
                     );
   }

   public string Name
   {
      get { return name; }
   }

   public string HexValue
   {
      get { return hexValue; }
   }

   private string name;
   private string hexValue;
}   

The Color class constructor takes a name, and the red, green, and blue values to describe the color. We can build an ArrayList of the class using the following code.

public static ArrayList GetColors()
{
   ArrayList list = new ArrayList();
   
   list.Add(new Color(System.Drawing.Color.AliceBlue.Name, 
                      System.Drawing.Color.AliceBlue.R,
                      System.Drawing.Color.AliceBlue.G,
                      System.Drawing.Color.AliceBlue.B)
            );

   list.Add(new Color(System.Drawing.Color.Beige.Name,
                      System.Drawing.Color.Beige.R,
                      System.Drawing.Color.Beige.G,
                      System.Drawing.Color.Beige.B)
            );

   list.Add(new Color(System.Drawing.Color.Chocolate.Name, 
                      System.Drawing.Color.Chocolate.R,
                      System.Drawing.Color.Chocolate.G,
                      System.Drawing.Color.Chocolate.B)
      );

   list.Add(new Color(System.Drawing.Color.DarkMagenta.Name,
                      System.Drawing.Color.DarkMagenta.R,
                      System.Drawing.Color.DarkMagenta.G,
                      System.Drawing.Color.DarkMagenta.B)
      );

   list.Add(new Color(System.Drawing.Color.Fuchsia.Name, 
                      System.Drawing.Color.Fuchsia.R,
                      System.Drawing.Color.Fuchsia.G,
                      System.Drawing.Color.Fuchsia.B)
      );

   list.Add(new Color(System.Drawing.Color.PapayaWhip.Name,
                      System.Drawing.Color.PapayaWhip.R,
                      System.Drawing.Color.PapayaWhip.G,
                      System.Drawing.Color.PapayaWhip.B)
      );

   list.Add(new Color(System.Drawing.Color.Violet.Name, 
                      System.Drawing.Color.Violet.R,
                      System.Drawing.Color.Violet.G,
                      System.Drawing.Color.Violet.B
                     )
      );

   list.Add(new Color(System.Drawing.Color.Black.Name, 
                      System.Drawing.Color.Black.R,
                      System.Drawing.Color.Black.G,
                      System.Drawing.Color.Black.B
                     )
        );
   return list;
}

Displaying values inside of <td> tags is not the only place to use a data binding expression. You can also use data binding to change the appearance of a control. In the next sample we will set the background color of a row using data binding.

<asp:Repeater id="Repeater1" runat="server">
  <ItemTemplate>
    <tr bgcolor="<%# DataBinder.Eval(Container.DataItem, "HexValue")%>">
      <td><%# DataBinder.Eval(Container.DataItem, "Name") %></td>
      <td><%# DataBinder.Eval(Container.DataItem, "HexValue") %></td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

This gives us the following form.

In the next section we will dig into see how data binding happens at runtime.

Under The Covers Of The Data Binding Expression

In order to really understand what happens inside of the data binding expression, let’s take a look at the code the runtime generates for the ASPX file.

public void __DataBind__control3(object sender, System.EventArgs e) {
   System.Web.UI.WebControls.RepeaterItem Container;
   System.Web.UI.DataBoundLiteralControl target;
   target = ((System.Web.UI.DataBoundLiteralControl)(sender));
   Container = ((System.Web.UI.WebControls.RepeaterItem)(target.BindingContainer));
       
   #line 17 "E:/dev/xprmnt/aspnet/DataBinding/SimpleData.aspx"
   target.SetDataBoundString(0, 
       System.Convert.ToString(DataBinder.Eval(Container.DataItem, "HexValue")));
            
   #line 18 "E:/dev/xprmnt/aspnet/DataBinding/SimpleData.aspx"
   target.SetDataBoundString(1, 
       System.Convert.ToString(DataBinder.Eval(Container.DataItem, "Name")));
             
   #line 19 "E:/dev/xprmnt/aspnet/DataBinding/SimpleData.aspx"
   target.SetDataBoundString(2, 
       System.Convert.ToString(DataBinder.Eval(Container.DataItem, "HexValue")));
       
}

The above is an excerpt from the code generated for our web form into the temporary ASP.NET files directory. It shows us how the Container variable that we use in the call to Eval is set to reference a BindingContainer setup by the runtime. This method, an event handler, will fire for each item the control needs to bind (once for each row, or once for each list item in this example).

The most important point to take from the above code is how the expression we use for data binding is placed as a parameter to Convert.ToString. This means we can use any expression that will yield a string. For example, the following ItemTemplate would produce the same screen we saw in the last screenshot.

<asp:Repeater id="Repeater1" runat="server">
  <ItemTemplate>
    <tr bgcolor="<%# ((Color)Container.DataItem).HexValue %>">	
      <td><%# ((Color)Container.DataItem).Name %></td>
      <td><%# ((Color)Container.DataItem).HexValue %></td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

In this case we are skipping a call to DataBind.Eval and casting the DataItem to our Color type (note, in order to do this, you’ll need to import the namespace used where Color is declared with the <@ Import > directive, i.e. <%@ Import Namespace="aspnet.DataBinding" %> if the Color type is in a class file under a namespace of aspnet.DataBinding.

Using the DataBinder.Eval technique allows us to avoid putting messy casts into the ASPX. Instead of casts, Eval uses reflection techniques to dynamically find a property by name at runtime. Because reflection is inherently slow, Eval is relatively slower than using a cast. On the other hand, one advantage to DataBinder.Eval is that the syntax will work in an ASPX compiled for either C# or VB.NET. In the form shown above the casting syntax will only work if the ASPX page compiles with the C# compiler.

While the above example demonstrates how we do not necessarily need to use DataBinder.Eval in our data binding expressions, let’s take the concept one step further and call a method in our code-behind class from the data binding expression.

<asp:Repeater id="Repeater1" runat="server">
  <ItemTemplate>
    <tr bgcolor="<%# ((Color)Container.DataItem).HexValue %>">
      <td><%# GetColorName(Container.DataItem)  %></td>
      <td><%# ((Color)Container.DataItem).HexValue %></td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

In the above template we call the GetColorName method and pass the DataItem as a parameter. Calling a method inside of a data binding expression allows us to use additional logic in the compiled, intellisensed environment of our code behind class. The method needs to be declared as a protected method of the code-behind class in order for this to work, because the class dynamically generated from the ASPX markup is derived from the class defined in the code behind file. The method in our code behind is shown below.

protected string GetColorName(object o)
{
   string name = string.Empty;

   Color color = o as Color;
   if(color != null)
   {
      name = color.Name;
      int i = 1;
      do
      {
         if(char.IsUpper(name, i))
         {
            name = name.Insert(i, " ");
            i = i +2;
         }
         else
         {
            i = i + 1;
         }

      } while(i < name.Length);
   }

   return name;
}

The method above will take the name of the color “PapayaWhip” and insert spaces in front of all uppercase letters after the first letter, yielding “Papaya Whip”.

Hopefully this article has demonstrated some additional techniques you can use in data binding scenarios. Don’t limit your self to DataBinder.Eval if the scenario calls for some additional formatting logic!

源码直接下载地址: https://pan.quark.cn/s/95437fdf229e Intel I-219V网卡驱动是一款专门为Intel的I-219V千兆以太网控制器而研发的驱动程序,其主要作用在于保障在Ubuntu 16.04操作系统环境下的正常运作以及优化系统性能。Intel I-219V作为一款广泛应用的内置网络接口控制器(NIC),常被集成在台式机及笔记本电脑的主板上,负责提供高速的网络连接服务。Intel公司所提供的e1000e驱动是与此硬件相配套的开源驱动解决方案,其中版本3.3.5.3是专门针对该硬件设备的定制版本。此驱动包含了不可或缺的源代码部分,赋予开发者和系统管理者按照特定需求进行编译和定制的权限,从而能够适应多样化的系统配置或针对特定情形进行问题解决。源代码的可用性同样表明用户有能力依据Linux内核的更新情况来升级驱动,确保与最新技术标准的兼容性。在Ubuntu 16.04系统中成功编译的驱动意味着它已经通过了严苛的测试流程,并能够与该版本的Linux内核实现良好兼容。Ubuntu 16.04,其代号为Xenial Xerus,是一个长期支持(LTS)的版本,因此对于那些追求系统稳定性和安全保障的用户群体而言具有特殊的意义。驱动程序的兼容性保障了I-219V网卡能够在该系统平台上实现无缝运行,提供稳定可靠的网络连接,这既包括局域网(LAN)的连接,也可能涵盖通过Wi-Fi桥接实现的无线网络连接。驱动程序的核心职责涵盖了网络接口的初始化与管理、数据包的接收与发送处理,以及错误检测与纠正功能的执行。在Linux操作系统架构中,驱动通常以模块的形式加载至内核之中,这种设计允许在非必要时期进行卸载操作,以此来有效节省系统资源。e1000e驱...
内容概要:本文围绕基于共识的捆绑算法(CBBA)在多智能体系统中的多任务分配问题展开研究,重点应用于远程太空船交会与维修的相对轨道操作(RPO)规划。通过Matlab代码实现了CBBA算法,系统地解决了多个航天器在复杂空间环境下协同执行多目标任务时的任务分配、路径规划与动态协商问题。研究详细展示了算法在任务分解、竞标机制、共识达成及冲突消解等方面的核心逻辑,验证了其在分布式决策、通信受限条件下的高效性与鲁棒性,并结合航天工程实际背景突出了算法的应用价值。该资源不仅提供完整的仿真代码,还包含详细的流程解析,有助于深入理解多智能体协同机制的设计原理。; 适合人群:具备控制理论、航天器动力学、多智能体系统或分布式优化背景的研究生、科研人员及航空航天领域工程技术人员,熟练掌握Matlab编程者尤佳。; 使用场景及目标:①应用于在轨服务、空间碎片清除、多航天器编队飞行、星座维护等多智能体协同任务的任务分配与规划;②为研究人员提供CBBA算法的实现范例,支撑其开展分布式任务规划算法的改进与扩展研究;③作为教学案例用于高级课程中讲解多智能体协同决策机制。; 阅读建议:建议结合Matlab代码逐模块分析算法实现过程,重点关注任务打包、竞标更新、共识收敛等关键环节,可尝试引入通信延迟、故障容错或障碍规避机制以进一步提升算法实用性。
内容概要:本文介绍了一种基于关键场景辨别算法的两阶段鲁棒微网优化调度方法,旨在有效应对风电等可再生能源出力不确定性带来的调度挑战。通过Matlab代码实现,构建了包含预调度与实时调整的两阶段鲁棒优化模型,第一阶段制定初始调度计划以应对不确定性,第二阶段根据实际运行数据进行修正,从而提升微网运行的经济性与可靠性。该方法结合场景生成与缩减技术,识别关键不确定性场景,降低计算复杂度,同时增强了调度方案的鲁棒性。文中还探讨了该方法与智能优化算法、机器学习及电力系统仿真工具的集成应用,展现了其在复杂综合能源系统中的广阔应用前景。; 适合人群:具备一定电力系统基础知识和Matlab编程能力,从事新能源、微网优化、不确定性建模与鲁棒调度等领域研究的科研人员、工程技术人员及研究生。; 使用场景及目标:①应用于高比例可再生能源接入的微电网优化调度,提高系统对源荷不确定性的适应能力与运行稳定性;②为科研人员提供可复现的两阶段鲁棒优化建模与求解范例,支撑高水平学术论文的复现、算法改进与创新研究。; 阅读建议:建议结合提供的Matlab代码与网盘资料,动手实践关键场景生成、不确定性建模、两阶段优化建模与求解全过程,重点关注鲁棒优化框架的设计逻辑与关键场景辨别的实现机制,同时参考文中提及的多种算法与工具,拓展研究思路与应用场景。
内容概要:本文系统阐述了基于二阶锥松弛(SOCPR)与线性离散最优潮流(OPF)模型的配电网规划(DNP)方法,并配套提供了完整的Matlab代码实现。研究聚焦于配电网中的复杂优化问题,通过构建精确的数学模型来描述功率流动、网络拓扑约束及多目标规划需求,旨在提升配电系统的运行效率、可靠性和对不确定性的适应能力。文中深入探讨了模型的构建逻辑,包括对非线性潮流方程的凸化处理与离散化求解策略,并结合智能优化算法有效应对新能源出力(如风电、光伏)与负荷需求的双重不确定性,为解决现代配电网扩容、重构及分布式电源接入等关键问题提供了理论依据和技术路径。此外,文档还关联了丰富的科研方向与技术支持内容,覆盖电力系统优化、微电网调度、不确定性建模与鲁棒优化等领域,凸显其在学术研究与工程实践中的双重价值。; 适合人群:具备电力系统分析、优化理论基础及Matlab编程能力的研究生、高校科研人员,以及从事电网规划、智能电网技术研发的工程师。; 使用场景及目标:①作为教学与科研工具,帮助理解配电网规划的核心原理、SOCPR与OPF模型的数学内涵及其实现细节;②为解决新能源大规模接入背景下配电网面临的不确定性、安全性与经济性协调优化问题提供可复现的算法参考;③作为开发更高级别的综合能源系统规划与鲁棒调度模型的技术基础与验证平台。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点剖析SOCPR松弛技巧与线性离散OPF模型的构建过程,通过调试与仿真加深对算法逻辑的理解。同时,可参考文档中提及的相关研究方向(如不确定性建模、鲁棒优化),拓展学习先进的优化技术与仿真方法,以全面提升解决复杂电力系统规划问题的综合能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值