expressions是asp.net 2.0中的新特色,它可以使你在asp.net的頁面裡很方便的使用自訂的屬性.
在ASPX頁裡只要使用$符號就可以訪問到,你定製的屬性了.
例如我們看個例子:
ASPX頁面中如下:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$connectionStrings:Pubs %>" SelectCommand="select * from catalog"></asp:SqlDataSource>
web.config檔案中如下: <configuration>
<appSettings/>
<connectionStrings>
<add name="Pubs" connectionString="server=localhost;database=getwant;Trusted_Connection=yes"/>
</connectionStrings>
</configuration>
因為在web.config中預設就有了connectionStrings的這個節點,所以我們很方便的使用add增加了一個屬性Pubs.
而如何自訂我們自己使用的節點呢?例如:<%$ Version:MajorMinor%>可以顯示當前環境下asp.net的主要版本號和次版本號碼呢?
如果我們直接在頁面中輸入上面的運算式,編譯器會告訴你,Version並沒有被定義,請在expressionBuilders節點中定製.其實這時候就要用到ExpressionBuilder類了.
System.Web.Compilation.ExpressionBuilder 就是expression builders的基類.
我們看看web.config中的設定:<compilation debug="true">
<expressionBuilders>
<add expressionPrefix="Version" type="VersionExpressionBuilder"/>
</expressionBuilders>
</compilation>
怎麼樣是不是很簡單呢?定義一個expressionPrefix為Version就可以了.
不過有人說那個type後面的是什麼意思呢,有VersionExpressionBuilder這個類嗎?
其實這個是我們自己繼承了ExpressionBuilder的類.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");
}
}
這時候我們在ASPX頁面中如下設定就可以通過編譯了: 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 "
怎麼樣是不是很簡單呢,呵...
本文參考了elearning的中的Custom Expression Builders章節.
時間非常緊張,家人催我吃飯,我就不多解釋了,如果有不懂的,可以給我留言.