Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.

I am sure that you all are familiar with Caching the page. If however you are interested that some portions of the page is not cached then you can make use of the Subsitution control which comes with ASP.NET 2.0. Simply, drag and drop the Subsitution control from the toolbox to the design view.

Here is the HTML of the Subsitution control:

<asp:Substitution ID="SubControl" runat="server" MethodName="GetDate" />  

The GetDate method is a static method (The method that you provide in the MethodName have to be a static method and must take HttpContext as a parameter). 

Here is the GetDate method: 

  public string GetDate(HttpContext context)
    {
        
return DateTime.Now.ToLongTimeString();                
    }

This method will be called whenever the page refreshes and even though you have enabled the caching on the page but subsitution control will display the updated information. 

The return type of the method has to be string. So, you can return simple Time as I showed you above or you can return different html elements such as table: 

 private static string GetData()
    {
        StringBuilder sb = 
new StringBuilder();
        sb.Append("<table border=\"1\" style=\"background-color: khaki\">"); 
        
        SqlConnection myConnection = 
new SqlConnection(ConnectionString);
        SqlCommand myCommand = 
new SqlCommand("SELECT * FROM Categories", myConnection);

        myConnection.Open();
        SqlDataReader reader = myCommand.ExecuteReader();
        
while (reader.Read())
        {
            sb.Append("<tr>");
            sb.Append("<td>");
            sb.Append((
int) reader["CategoryID"]);
            sb.Append("</td>");
            sb.Append("<td>");
            sb.Append((
string)reader["CategoryName"]);
            sb.Append("</td>");
            sb.Append("<td>");
            sb.Append(DateTime.Now.ToLongTimeString());
            sb.Append("</td>"); 
            sb.Append("</tr>"); 

        }

        myConnection.Close();
        reader.Close();
        myCommand.Dispose(); 

        sb.Append("</table>");

        
return sb.ToString(); 

    }

The static method will look something like this: 

 public string GetDate(HttpContext context)
    {
        
return GetData();
    }

I think it would be really cool if we could add web server controls like GridView, Datagrid and other controls into the subsitution controls and hence those controls inside the Subsitution control will not be cached.

       

powered by IMHO 1.3

Posted on Saturday, March 4, 2006 3:30 PM | Back to top


Comments on this post: Subsitution Control in ASP.NET 2.0

# re: Subsitution Control in ASP.NET 2.0
Requesting Gravatar...
Nice Example
Left by ASHUTOSH on Mar 25, 2008 7:04 PM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net