ASP.NET Substitution 控件的使用方法


在某些情况下,可能要缓存 ASP.NET 页,但需根据每个请求更新页上选定的部分。例如,您可能要缓存某页的很大一部分,但需要动态更新该页上的与时间高度相关的信息。

可以使用 Substitution 控件将动态内容插入到缓存页中。Substitution 控件不会呈现任何标记。您需要将该控件绑定到页上或父用户控件上的方法中。您要自行创建静态方法,以返回要插入到页中的任何信息。由 Substitution 控件调用的方法必须符合下面的标准:

此方法被定义为静态方法(在 Visual Basic 中为共享方法)。

此方法接受 HttpContext 类型的参数。

此方法返回 String 类型的值。

注意,Substitution 控件无法访问页上的其他控件,也就是说,您无法检查或更改其他控件的值。但是,代码确实可以使用传递给它的参数来访问当前页上下文。

在页运行时,Substitution 控件会调用该方法,然后用从该方法的返回值替换页上的 Substitution 控件。

下面分别用两种方式演示 Substitution 控件在缓存页上生成动态的内容,缓存时间为20秒,20秒内无论刷新多少次,直接输出的时间都不变。而页面上的 Substitution 控件调用静态方法 getCurrentTime,每次调用都是变化的。

代码一:使用Response.Cache相关方法设置缓存

复制代码 代码如下:

<script runat="server">
    static string getCurrentTime(HttpContext context)
    {
        return DateTime.Now.ToString();
    }
    void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(20));
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetValidUntilExpires(true);
    }
</script>
<div>
    <h4>
        在缓存页面插入动态内容--使用substitution控件演示</h4>
    <p>
        Cache Time:<%= DateTime.Now.ToString() %>
    </p>
    <p>
        <b>Real Time:<asp:Substitution ID="Substitution1" runat="server" MethodName="getCurrentTime" />
        </b>
    </p>
</div>

代码二:使用OutputCache命令设置缓存

复制代码 代码如下:

<%@ OutputCache Duration="20" VaryByParam="none" %>
<script runat="server">
    static string getCurrentTime(HttpContext context)
    {
        return DateTime.Now.ToString();
    }
</script>
<div>
    <h4>
        在缓存页面插入动态内容--使用substitution控件演示</h4>
    <p>
        Cache Time:
        <%= DateTime.Now.ToString() %>
    </p>
    <p>
        <b>Real Time:<asp:substitution id="Substitution1" runat="server" methodname="getCurrentTime" />
        </b>
    </p>
</div>


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3