Search

Aug 4, 2008

Expression in ASP.NET

What if I want to show the value of the key defined in Web.config file on a ASPX page? Or for testing purpose if we want to show the value of connection string??

Here is the Web.Config file entries...
<appSettings>
<add key="ImageFolder" value="C:\Temp"/>
</appSettings>
<connectionStrings>
<add name="DBConnection" providerName="System.Data.SqlClient"
connectionString="Data Source=[DataSource];Initial Catalog=[InitialCatalog];
User ID=[UserID];Password=[Password]"
/>
</connectionStrings>
And here is the general code:
Response.Write(ConfigurationManager.AppSettings["ImageFolder"]);
Response.Write(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
Now lets use the expression....
<asp:Label ID="lblDBConnection" runat="server" Text='<%$ connectionStrings:DBConnection %>' />
<asp:Label ID="lblImageFolder" runat="server" Text='<%$ appSettings:ImageFolder %>' />

So simple!!!
The <%$ and %> tags are used to mark an expression that should be parsed by an ExpressionBuilder. Because of the prefix ConnectionStrings and appSettigs are already mapped to the particular ExpressionBuilder class that is responsible for parsing the expression; we dont need to do any extra afford.

Here are the default ExpressionBuilder classes provided by ASP.NET framework.


  1.  AppSettingsExpressionBuilderRetrieves values from the appSettings section of the web configuration file.

  2.  ConnectionStringsExpressionBuilderRetrieves values from the connectionStrings section of the web configuration file.

  3.  ResourceExpressionBuilderRetrieves values from resource files.



The ExpressionBuilder must always be used with control properties as I used in my example. You can create a custom ExpressionBuilder when none of the existing ExpressionBuilder classes do what you need, for this you must implement the ExpressionBuilder abstract class. Read More

No comments: