加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何LoadControl一个使用VaryByControl OutputCache

发布时间:2020-12-16 07:16:09 所属栏目:asp.Net 来源:网络整理
导读:我有一个应该使用缓存的用户控件,使用VaryByControl. .ascx文件如下所示: %@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="mynamespace.TestControl" %%@ OutputCache Duration="10" Shared="true" VaryByCon
我有一个应该使用缓存的用户控件,使用VaryByControl. .ascx文件如下所示:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="mynamespace.TestControl" %>
<%@ OutputCache Duration="10" Shared="true" VaryByControl="Test" %>
<p id="SomeText" runat="server">Nothing</p>

代码隐藏文件中的TestControl类具有int Test {…}属性和Page_Load()事件处理程序,该处理程序用以下内容填充SomeText段落:

SomeText.InnerText = string.Format(@"Test={0} at {1}",Test,DateTime.Now)

我有一个.aspx文件看起来像这样:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="mynamespace.TestPage" %>
<%@ Register TagPrefix="xxx" TagName="TestControl" Src="ControlsTestControl.ascx" %>

<!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></title>
</head>
<body>
    <xxx:TestControl Test="6" runat="server" />
    <xxx:TestControl Test="7" runat="server" />
    <hr />
    <asp:PlaceHolder ID="Suport" runat="server" />
</body>
</html>

两个< xxx:TestControl>标签正确加载TestControl的实例与测试设置为期望值,我可以刷新浏览器几次,我可以看到缓存正确地完成它的工作.

现在我要填写< asp:PlaceHolder ID =“Suport”/>使用一些TestControl实例,使用不同的Test值,这些实例都应该从正确的缓存中获益.我正在尝试使用LoadControl方法,但我找不到为Test属性指定值的方法.在加载.aspx页面的所有asp.net代码设法找到正确的缓存控件之后,我希望这样的方法存在.我得到的是PartialCachingControl的一个实例,没有初始化CachedControl,在运行时,渲染的TestControl显示Test的默认值为0.

这就是我的.aspx Page_Load()事件处理程序的样子:

protected void Page_Load(object sender,EventArgs e)
{
    PartialCachingControl tc = (PartialCachingControl) LoadControl(@"ControlsTestControl.ascx");
    if (tc.CachedControl != null)
        ((TestControl)tc.CachedControl).Test = 67;            
    Suport.Controls.Add(tc);
}

编辑

我可以通过缓存整个页面来解决这个问题,但这似乎很奇怪我无法通过这种方式找到方法.特别是因为通过ASPX文件调用控件按预期工作(证明有一种方法).

编辑2

嗯,到目前为止还没有答案.我开始获得赏金,希望它得到更多的关注.

解决方法

我认为您误解了VarByControl属性,它不会告诉缓存更改控件上的属性,而是指示页面上控件的ID. Here is the text from MSDN:

The VaryByControl property is set to fully qualified control identifiers,where the identifier is a concatenation of control IDs starting from the top-level parent control and delimited with a dollar sign ($) character.

在您的情况下,您可以设置VaryByCustom而不是VaryByControl,并从Test-property-value生成缓存键,如果更改则更改它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读