簡體   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