關於如何在ASP.NET 2.0中定製Expression Builders

來源:互聯網
上載者:User

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章節.

時間非常緊張,家人催我吃飯,我就不多解釋了,如果有不懂的,可以給我留言.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.