Cache specific section of Page in ASP.Net using C# and VB.Net

Last Reply 6 months ago By pandeyism

Posted 6 months ago

i want to cache the portion of a page instead of whole page?

You are viewing reply posted by: pandeyism 6 months ago.
Posted 6 months ago

Hey khatri852,

Please refer below sample.

HTML

<%@ OutputCache Duration="5" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Substitution Class Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
        This section of the page is not cached:</p>
    <asp:Substitution ID="Substitution1" MethodName="GetCurrentDateTime" runat="Server">
    </asp:Substitution>
    <br />
    <p>
        This section of the page is cached:</p>
    <asp:Label ID="lblDate" runat="Server">
    </asp:Label>
    </form>
</body>
</html>

Code

protected void Page_Load(object sender, EventArgs e)
{
    lblDate.Text = DateTime.Now.ToString();
}

public static string GetCurrentDateTime(HttpContext context)
{
    return DateTime.Now.ToString();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    lblDate.Text = DateTime.Now.ToString()
End Sub

Public Shared Function GetCurrentDateTime(ByVal context As HttpContext) As String
    Return DateTime.Now.ToString()
End Function

Screenshot