日期:2014-05-16  浏览次数:20816 次

教你30秒打造强类型ASP.NET数据绑定

数据绑定似乎是ASP.NET老掉牙的东西了。可是你知道吗,只需要一点小小的改动就可以替换Eval,摆脱字符串依赖并且大大提高性能。

首先在code behind中加入以下方法

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->protected virtual object ExpHelper<TEntity, TREsult>(Func<TEntity, TREsult> func) { var itm = GetDataItem(); return func((TEntity)itm); }

这段代码就是最核心的秘诀了,你完全可以忽视它到底在做什么。其实就是截获每一个被绑定的数据项,并进行强类型转换。

假设我们定义了学生类

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->public class Student { public string Name { get; set; } public int Age { get; set; } }

如果希望在页面中使用强类型访问学生类而不是用Eval,定义专门访问学生的方法

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->protected object Stu<TResult>(Func<Student, TResult> func) { return ExpHelper<Student, TResult>(func); }

大功告成,于是在页面里我们就能这样绑定数据了

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --><ul> <asp:Repeater ID="rptStudents" runat="server"> <ItemTemplate