0
点赞
收藏
分享

微信扫一扫

如何在ASP.NET 2.0中定制Expression Builders

霍华德 2022-12-26 阅读 113

expressions是asp.net 2.0中的新特色,它可以使你在asp.net的页面里很方便的使用自定义的属性.
在ASPX页里只要使用$符号就可以访问到,你定制的属性了.
例如我们看个例子:
ASPX页面中如下:


如何在ASP.NET 2.0中定制Expression Builders_asp.net

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$connectionStrings:Pubs %>" SelectCommand="select * from catalog"></asp:SqlDataSource>


web.config文件中如下:


<configuration> 
<appSettings/>
<connectionStrings>
<add name="Pubs" cnotallow="server=localhost;database=getwant;Trusted_Cnotallow=yes"/>
</connectionStrings>
</configuration>

因为在web.config中默认就有了connectionStrings的这个节点,所以我们很方便的使用add增加了一个属性Pubs.

而如何自定义我们自己使用的节点呢?例如:<%$ Version:MajorMinor%>可以显示当前环境下asp.net的主版本号和次版本号呢?

如果我们直接在页面中输入上面的表达式,编译器会告诉你,Version并没有被定义,请在expressionBuilders节点中定制.其实这时候就要用到ExpressionBuilder类了.


System.Web.Compilation.ExpressionBuilder 就是expression builders的基类.

我们看看web.config中的设置:


如何在ASP.NET 2.0中定制Expression Builders_asp.net

<compilation debug="true">
<expressionBuilders>
<add expressinotallow="Version" type="VersionExpressionBuilder"/>
</expressionBuilders>
</compilation>怎么样是不是很简单呢?定义一个expressionPrefix为Version就可以了.

不过有人说那个type后面的是什么意思呢,有VersionExpressionBuilder这个类吗?

其实这个是我们自己继承了ExpressionBuilder的类.

}这时候我们在ASPX页面中如下设置就可以通过编译了:

public class VersionExpressionBuilder:ExpressionBuilder
{
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,object parsedData,ExpressionBuilderContext context)

{
string param = entry.Expression;
if (string.Compare(param, "All", true) == 0)

{
return new CodePrimitiveExpression(string.Format("{0}.{1},{2}.{3}", Environment.Version.Major, Environment.Version.Minor, +
Environment.Version.Build, Environment.Version.Revision));
}
else if (string.Compare(param, "MajorMinor", true) == 0)

{
return new CodePrimitiveExpression(string.Format("{0}.{1}", Environment.Version.Major, Environment.Version.Minor));
}
else
throw new InvalidOperationException("User $ Version:All or $ Version:MajorMinor");
}


如何在ASP.NET 2.0中定制Expression Builders_asp.net

 ASP.NET  <asp:Literal ID="Literal1" runat="server" Text="<% $ Version:MajorMinor %>"></asp:Literal>显示的为"ASP.NET 2.0"

把表示式改为:<%$ Version:All %>就会显示为"ASP.NET 2.0,50727.42 "


Expression builders ​​1​​​ ​​2​​ - a nice way to assign property values in web controls















举报

相关推荐

0 条评论