日期:2014-05-17  浏览次数:20442 次

如何使基于DropDownList的VaryByControl缓存的内容立刻无效
问题在第三步,请仔细看第三步

第一步
dropdownlist里有三项,分别代表三种类别的书:C#,C++,Java
通过dropdownlist选择不同的类别后,触发的drpBookSort_selectedIndexChanged事件会把
属于被选中类别的所有书都显出来了,第一步很正常。

第二步
为了提高速度我用了如下缓存
<%@ OutputCache Duration="1000" VaryByParam="none" VaryByControl="drpBookSort"%>
现在虽然不会触发drpBookSort_selectedIndexChanged事件,
但是通过dropdownlist选择不同的类别后,仍然能显示不同类别的所有书,第二步也正常



第三步
问题是当我在C#类别下又新加一本书比如《C#高级编程》,可是由于缓存的原因,我发现新加的书显不出来,
而且drpBookSort_selectedIndexChanged事件,也因为缓存的原因不被触发了,
请问有没有简单的代码,使那个VaryByControl的缓存暂时无效,把新加的数据也显示出来,然后再缓存


------解决方案--------------------
你可以随意自定义控制机制。

例如写
<%@ Page Language="C#" %>

<%@ OutputCache Duration="3600" VaryByParam="none" VaryByCustom="mytest1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Label1.DataBind();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>测试VaryByCustom</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="<%# DateTime.Now.ToString() %>" EnableViewState="false"></asp:Label>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />    
</form>
</body>
</html>


以及在global.asax中写
    public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom == "mytest1")
        {
            var val = context.Cache["t1"];
            if (val == null)
                return string.Empty;
            else
        &nb