简体   繁体   中英

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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