2011-01-29 30 views
1

如何在母版页中声明名为MyDic的字典?在主页中声明会话字典

我希望MyDic能够保存对象MyObj的列表,并将日期作为关键字,以便我可以这样写:“从MyDic获取日期1/28/2011的列表”或“将MyObj的这个列表从2011年1月28日在MyDic“。

我想在母版页中声明字典,以便我可以在每个页面中访问它。

谢谢。

回答

2

你打算如何坚持清单? 而不是在母版页中创建它,你可以创建它作为应用程序变量,或者如果它是用户特定的会话变量。在这两种情况下,你会做这样的事情:

Dictionary<DateTime, myObj> myList = new Dictionary<DateTime, myObj>(); 

那么你将它存储在某处:

Session["MyList"] = myList; 

,当你需要再次访问它:

Dictionary<DateTime, myObj> myList = (Dictionary<DateTime, myObj>)Session["MyList"]; 

你可以这样做声明在母版页上初始化或加载,甚至更好,我会建议在global.asax文件中进行会话或应用程序

+0

好的,非常感谢,这正是我一直在寻找的! – frenchie 2011-01-29 20:43:11

+0

没有我回答几个小时前你这里几乎相同的问题在这里..http://stackoverflow.com/questions/4838129/storing-dictionary-in-session/4838354#4838354? – BrokenGlass 2011-01-29 20:46:25

0

对于这种共享,您可以使用sessionapplication变量。

这种情况几乎是他们创造的。

+0

这也行吗? Dictionary > SessionFolders = new Dictionary >();这会创建一个列表字典吗? – frenchie 2011-01-29 20:48:44

2

您可以在Master页面上创建公共属性,然后通过设置MasterType指令将其用于内容页面。例如如果有一个名为MyMasterPage母版页,然后这里是代码示例

/// declare it in Master Page 
public Dictionary<DateTime, typeof(List<MyObj_Type>)> MyDic { 
     get; 
     set; 
} 

/// put the line just under Page directive on your content page where you want to access it 

<%@ MasterType virtualPath="~/MyMasterPage.master"%> 

/// and then on content page you can access by 
** Note: The intelisense may not work but don't worry just put the code in content page and it works.** 

Master.MyDic.Add(DateTime.Now, MyObj); 

下面是详细信息Accessing Members on the Master Page

如何有一个好的一天!