繁体   English   中英

如何在缓存C#中存储多个数据

[英]How to store multiple data in cache c#

嗨,我有一个用户控件,我要在特定页面中多次调用它,以下是该代码

 private void BindMenu()
        {
            string menuContent = (string)Cache[_CacheKey];
            if (string.IsNullOrEmpty(menuContent))
            {                
                menuContent = GenerateMenu(CategoryId, 1);             
                Cache.Add(_CacheKey, menuContent, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            phMenu.Text = menuContent;
        }

现在,由于我要传递不同的类别ID(例如1,2,3),因此多次调用了“绑定”菜单。

但是,一旦传递了类别ID 1,它就会将数据存储在缓存中,然后在同一页面上重复用户控制后,它总是将显示的数据显示在缓存中。

我曾尝试删除缓存逻辑,并且根据我的结果,数据反映的是用户控件显示的内容,但这增加了页面加载时间。

有帮助吗?

解决的问题

 private void BindMenu()
        {
            string menuContent = (string)Cache[_CacheKey+Convert.ToString(CategoryId)];
            if (string.IsNullOrEmpty(menuContent))
            {                
                menuContent = GenerateMenu(CategoryId, 1);             
                Cache.Add(_CacheKey+Convert.ToString(CategoryId), menuContent, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            phMenu.Text = menuContent;
        }

使用缓存将参数传递给Web用户控件是一个坏主意。

您需要使用属性

在用户控件的代码中声明一个public int变量,并在其set函数中使用传递的value

在用户控件的代码后面:

// Declare a public property
public int CategoryId 
{ 
   set
   {
       // use the value keyword to get the value passed from the main page:
       if (string.IsNullOrEmpty(menuContent))
       {                
           menuContent = GenerateMenu(value, 1);  
           phMenu.Text = menuContent;             
       }
   }
}

在调用(包含)页面的代码中:

UserControl1.CategoryId = 1;
UserControl2.CategoryId = 2;
....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM