[英]Unable to cast System.String to type System.Collections.Generic.Dictionary<string, string> with Session variable
Hi all and thanks in advance. 大家好,谢谢。 I have some code I'm trying to fix where I'm getting the 我有一些代码正在尝试修复我在哪里得到的
error message: Unable to cast
System.String
to typeSystem.Collections.Generic.Dictionary<string, string>
错误消息:无法将System.String
转换为System.Collections.Generic.Dictionary<string, string>
but I can't figure out which portion of the code is being interpreted as a System.String and being inserted into the session variable causing the cast to Dictionary<string, string>
to break. 但是我无法弄清楚代码的哪一部分被解释为System.String并插入到会话变量中,从而导致对Dictionary<string, string>
转换中断。
The code is fairly simple, this declaration: 该代码相当简单,此声明如下:
Dictionary<string, string> myControls;
private readonly string SCONTROLS = "smControls";
In OnInit: 在OnInit中:
if(!isPostBack)
{
myControls = new Dictionary<string, string>();
Session[SCONTROLS] = myControls;
}
else
{
if (Session[SCONTROLS] != null)
{
myControls = (Dictionary<string,string>)Session[SCONTROLS];
if (myControls != null)
foreach (var controlID in myControls.Keys)
{
UserControl controlToAdd = new UserControl();
controlToAdd = (UserControl)controlToAdd.LoadControl(myControls[controlID]);
controlToAdd.ID = controlID;
formatPlaceHolder(controlToAdd);
}
}
}
Then in a separate section where there is a control, some of the values are being updated: 然后在有控件的单独部分中,一些值正在更新:
UserControl uc = DefaultControl as UserControl;
if (uc != null)
{
uc.ID = Guid.NewGuid().ToString();
formatPlaceHolder(uc);
if (!myControls.Keys.Contains(uc.ID))
myControls.Add(uc.ID, uc.AppRelativeVirtualPath);
else
myControls[uc.ID] = uc.AppRelativeVirtualPath;
DefaultControl.LoadNewItem(item, uc.ID, Master.EmpID.Value, ShowRemove, Master.ID);
}
I have speculated that maybe part of the problem is that when myControls
is altered it's never saved into the Session variable so when it tries to do the cast from the Session variable is basically just empty. 我推测问题的一部分可能是,当myControls
更改时,它从未保存到Session变量中,因此,当它尝试从Session变量进行myControls
类型转换时,它基本上只是空的。 But since it was initialized as a Dictionary<string,string>
object to start with I would think it wouldn't matter if it were still empty? 但是由于它被初始化为从Dictionary<string,string>
开始的Dictionary<string,string>
对象,所以我认为如果它仍然为空也没关系?
Or is the problem that it isn't initializing properly inside the OnInit
function? 还是在OnInit
函数内部无法正确初始化的问题?
Updating information: 更新信息:
The values in the Session variable look like this: Session变量中的值如下所示:
Key: c52acd20-8d3e-44cc-bc79-8fee9c9c3064
Value: "~/Questions.ascx"
Did you put quote around string intentionally? 您是否故意在字符串周围加上引号? I think it should be, myControls = (Dictionary)Session[SCONTROLS]; 我认为应该是,myControls =(Dictionary)Session [SCONTROLS];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.