简体   繁体   English

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

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

Hi I have one user control which I am calling multiple times in particular page, and below is the code for that 嗨,我有一个用户控件,我要在特定页面中多次调用它,以下是该代码

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

Now the Bind menu is called multiple times as I am passing different category Id like 1,2,3. 现在,由于我要传递不同的类别ID(例如1,2,3),因此多次调用了“绑定”菜单。

But once the category Id of 1 is passed it stores it data in cache and then after when user control is repeated on same page it always shows stored data as show in cache. 但是,一旦传递了类别ID 1,它就会将数据存储在缓存中,然后在同一页面上重复用户控制后,它总是将显示的数据显示在缓存中。

I had tried removing cache logic and the data reflect is user control shows as per my result but it is increasing the page loading time. 我曾尝试删除缓存逻辑,并且根据我的结果,数据反映的是用户控件显示的内容,但这增加了页面加载时间。

Any Help? 有帮助吗?

Resolved Issue 解决的问题

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

Using cache to pass parameters to a web user control is a bad idea. 使用缓存将参数传递给Web用户控件是一个坏主意。

You need to use properties . 您需要使用属性

Declare a public int variable in the User Control's' code, and in its set function, use the value passed. 在用户控件的代码中声明一个public int变量,并在其set函数中使用传递的value

In the user control's code behind: 在用户控件的代码后面:

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

In the calling (containing) page's code: 在调用(包含)页面的代码中:

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

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

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