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

时间:2017-11-03 15:04:30

标签: c# asp.net caching

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

 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;
        }

现在多次调用Bind菜单,因为我传递了不同的类别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;
        }

1 个答案:

答案 0 :(得分:0)

使用缓存将参数传递给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;
....
相关问题