In Asp.Net we can cache the entire page by using OutputCache attribute. But sometimes we have to clear the cache for specific control action. That means for example we have drop down list and Button control on asp.net page, we have to clear the cache for drop down list item selection but not for button control action.
We can achieve this by using VaryByControl attribute of OutputCache. Just mention control id for which you want to clear the cache for VaryByControl attribute as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache Duration="3600" VaryByControl="ddl" 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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=DateTime.Now.ToString() %> <br />
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl_OnSelectedIndexChanged" ></asp:DropDownList>
<asp:Button ID="btn1" runat="server" Text="Check For Cache" />
</div>
</form>
</body>
</html>
As shown above we have drop down list control ddl and Button control btn1. We provided the drop down list control id ddl for VaryByControl attribute for OutputCache. Bind the drop down list with XML file data source as shown below.
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("Employee.xml"));
ddl.DataSource = ds.Tables[0];
ddl.DataTextField = "name";
ddl.DataValueField = "id";
ddl.DataBind();
We are displaying the current date and time to check whether page is cached or not. Now run the application and change the drop down list value, you will find that current time is changing because we mention the drop down list control id for VaryByControl attribute. Click the Button Control, this time current time is not changing because the page is cached for 3600 seconds.