您的位置:首页 > 编程语言 > ASP

ASP.NET中使用反射将控件值与实体值相互映射

2008-05-24 16:25 218 查看
在ASP.NET中, 我们要获取控件的值, 或是给控件赋值, 一般都是Control.Property = Entity.Property, Entity.Property = Control.Property.
如果控件太多,这样写就显的繁琐,而且容易出错.
这种情况下, 使用反射, 把符合控件名和实体属性名相同的值相互映射,只要一行代码就可以完成操作了.

来看主要的两个方法签名:



public static void ControlsToEntity(Control container, object entity, bool isContainChildren, string controlIDFormat, params KeyValuePair<string, Type>[] customMaps)

public static void EntityToControls(object entity, Control container, bool isContainChildren, string controlIDFormat, params KeyValuePair<string, Type>[] customMaps)

然后是测试用例, 不太容易理解, 见谅:

public class Entity

public class Custom : Control

[TestClass()]
public class ControlMappingTest

之后我又有了新的想法, 就是在中间加入一层Hash值, 这样就可以实现UI层的解藕, 即Control <=> Hash <=> Entity.
暂时只实现了Control <=> Hash :

public static Dictionary<string, object> ControlsToHash(Control container, bool isContainChildren, params string[] customProperties)

public static void HashToControls(Dictionary<string, object> hash, Control container, bool isContainChildren, params string[] customProperties)

测试用例:

[TestMethod]
public void ControlsToHashAndHashToControlsTest()
测试数据准备#region 测试数据准备

Control container = new Control();

Label c_UserID = new Label() TextBox c_UserName = new TextBox()
Control otherInfo = new Control();
DropDownList c_Age = new DropDownList() c_Age.Items.Add(new ListItem("1"));
DropDownList c_IsUsed = new DropDownList() c_IsUsed.Items.Add(new ListItem("True"));
otherInfo.Controls.Add(c_Age, c_IsUsed);

RadioButtonList c_RoleID = new RadioButtonList() c_RoleID.Items.Add(new ListItem("2"));

container.Controls.Add(c_UserID, c_UserName, otherInfo, c_RoleID);

#endregion

Dictionary<string, object> expectedHash = new Dictionary<string, object>();
expectedHash.Add("c_UserID", "1");
expectedHash.Add("c_UserName", "Xiaosonl");
expectedHash.Add("c_Age", "1");
expectedHash.Add("c_IsUsed", "True");
expectedHash.Add("c_RoleID", "2");

ControlMapping.HashToControls(expectedHash, container, true);

Dictionary<string, object> hash = ControlMapping.ControlsToHash(container, false);
Assert.AreEqual(false, hash.SerializeEqual(expectedHash));
hash = ControlMapping.ControlsToHash(container, true);
Assert.AreEqual(true, hash.SerializeEqual(expectedHash));
}

具体实现代码见FastDev.Web.ControlMapping类.
下载FastDev.Web.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: