一般情况下,Asp.net页面,需要呈现后台的实体数据,比如展示一个人员的基本信息。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoDataBind.aspx.cs" Inherits="AutoDataBind" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id = "bindArea" runat="server">
姓名:<asp:Label ID="_Name" runat="server" Text="Label"></asp:Label>
<br />
年龄:<asp:Label ID="_Age" runat="server" Text="Label"></asp:Label>
<br />
简介:<br />
<asp:TextBox ID="_Memo" runat="server" Height="123px" TextMode="MultiLine"
Width="605px"></asp:TextBox>
</div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server">
</asp:ObjectDataSource>
</form>
</body>
</html>
通常情况下,我们需要在后台写这样的代码:
_Name.Text = Person.Name;
才能把实体的值填充到界面上,实际上这是个枯燥的苦力活,尤其是做一些项目开始的时候,有大量的界面需要绑定数据,而且需求又变化快。
那么我们希望自动绑定就比较好,比如象绑定表格一样, GridView = DataSource; GridView.DataBind(); 实际上我们通过后台来调用反射,自动把属性绑定上就可以了。可能你已经注意到上面需要绑定的变量名都有个"_"前缀,这就是为了区别需要绑定的对象的命名规则。
下面是后台绑定代码的例子:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
public partial class AutoDataBind : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Person person = new Person();
person.Name = "张三";
person.Age = 99;
person.Memo = "饭后百步走,活到99";
DataBindHelper.Bind(bindArea, person);
}
}
public class DataBindHelper
{
public static void Bind(System.Web.UI.HtmlControls.HtmlGenericControl bindArea, object person)
{
Type type = person.GetType();
foreach (PropertyInfo item in type.GetProperties())
{
Control control = bindArea.FindControl("_" + item.Name);
if (control != null)
{
if (control.GetType() == typeof(Label)) ((Label)control).Text = item.GetValue(person, null).ToString();
if (control.GetType() == typeof(TextBox)) ((TextBox)control).Text = item.GetValue(person, null).ToString();
}
}
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Memo { get; set; }
}
例子比较简单,实际应用上可以扩展的更丰富一些,另外反射能降低性能,此方法可以适用在对性能要求不高,需求变化又快的小项目上。
欢迎转载,转载请注明出处及署名:月光下的凤尾族:http://www.cnblogs.com/demo/
欢迎到此快速关注 谢谢