2012-10-12 18 views
2

我們可以存儲應用水平字符串像一個Global.asax文件: 全球ASAX:店在Global.asax中列出

void Application_Start(object sender, EventArgs e) 
    { 
     Application.Lock(); 
     Application["msg"] = "";    
     Application.UnLock();   
    } 

然後在頁中,我們得到了「味精」變量: a.aspx.cs:

protected void Page_Load(object sender, EventArgs e) 
{ 
     string msg = (string)Application["msg"]; 
     //manipulating msg.. 
} 

不過,我想存儲對象的應用程序級變量的列表,而不是的字符串味精。我嘗試這樣做: 的Global.asax:

void Application_Start(object sender, EventArgs e) 
    { 
     Application.Lock(); 
     List<MyClassName> myobjects= new List<MyClassName>();  
     Application.UnLock();   
    } 

a.aspx.cs:

protected void Page_Load(object sender, EventArgs e) 
    { 
     //here I want to get myobjects from the global.asax and manipulate with it.. 
    } 

那麼,如何存儲列表myobjects在全球的應用程序級的變量.asax和這個工作?

此外,我還有一個問題: 如何任何通知發送給客戶端(瀏覽器)時,在Global.asax的全局變量發生變化?

+0

這是什麼網站或web應用? – yogi

+0

它是WebSite,否則我們不能添加global.asax文件 – Nurlan

回答

1

一種方法是將其存儲到緩存:

using System.Web.Caching;  

protected void Application_Start() 
{ 
    ... 
    List<MyClassName> myobjects = new List<MyClassName>(); 
    HttpContext.Current.Cache["List"] = myobjects; 
} 

然後訪問/操縱它:

using System.Web.Caching; 

var myobjects = (List<MyClassName>)HttpContext.Cache["List"]; 
//Changes to myobjects 
... 
HttpContext.Cache["List"] = myobjects; 
+0

最後給出編譯錯誤說:「對於非靜態方法或字段HttpContex.Cache.get」引用該對象是必要的「 – Nurlan

+0

你從哪裏得到這個錯誤 –

+0

Evertything現在可以,但是你在訪問時忘了單詞「current」,它必須是var myobjects =(列表)HttpContext.Current.Cache [ 「List」]; – Nurlan