简体   繁体   English

动态创建不同的会话变量

[英]Dynamically Create Different Session Variables

I was wondering if it was possible to dynamically create different session variables with different names based on a variable? 我想知道是否可以基于变量动态创建具有不同名称的不同会话变量?

I attempted to accomplish this way but does not seem to like my variable 我尝试完成这种方式,但似乎不喜欢我的变量

protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    LinkButton lb = (LinkButton)e.Row.FindControl("MyLinkButton");
    Label options = (Label)e.Row.FindControl("MyLabel");
    if (e.Row.RowType == DataControlRowType.DataRoow)
    {
    Session[lb] = options;  
//I was trying to use this to create Session Variables with Different Names Dynamically
    }

}

So my end result I would have the following sessions with out having to manually create all of them. 因此,我的最终结果将是进行以下会话,而无需手动创建所有会话。

Session["Value"] = "MyOption"
Session["Value1"] = "MyOption1"
Session["Value2"] = "MyOption2"
Session["Value3"] = "MyOption3"

You're doing it backward. 您正在倒退。 Since you are in the RowDataBound Event, clearly you are data binding. 由于您处于RowDataBound事件中,因此显然您是在进行数据绑定。 So save the data in Session["DataSource"] or something like that, instead of re-creating the data set when you bind it row by row. 因此,将数据保存在Session["DataSource"]或类似的文件中,而不是在逐行绑定数据集时重新创建数据集。

I suggest ViewState because it's only valid for that page. 我建议使用ViewState,因为它仅对该页面有效。 If you don't plan on using the data outside of that page, there's no reason to add it to Session. 如果您不打算使用该页面之外的数据,则没有理由将其添加到Session中。

What are you using the Session data for? 您将Session数据用于什么?

You can create a list of sections. 您可以创建部分列表。 For exaple: 例如:

List<string> sections=GetSectionsList();

The for each item in your list create a Session variable and populate with the status, something like this: 为您列表中的每个项目创建一个Session变量并填充状态,如下所示:

foreach(string section in sections)
{
   Session[section] = GetSectionStatus(section);
}

Then onload of each section check for the sections session value and act accordingly. 然后每个部分的onload检查部分会话值并采取相应措施。 But a piece of advice there use session for this situation only if the sections are considerably less in number say 2 to 5, else a db call on load of each section would be better. 但是,只有在节的数目要少得多(例如2到5)的情况下,那里的一条建议才使用会话,否则对每个节的负载进行db调用会更好。

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

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