当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Substitution 控件的使用方法

ASP.NET Substitution 控件的使用方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

钱海英,科洛弗档案2,人民币白银价格

在某些情况下,可能要缓存 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>

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网