我有一个问题和答案页面,当一些问题被隐藏,一些问题取决于前任的答案。最后我需要所有的答案。 我正在尝试使用字典。我用每个控件的更改事件的键添加答案。但是当我移动到下一部分时,没有一个答案被保存,因为我隐藏了前面的部分。
我正在尝试将其保存在视图状态中并添加值,以便我的值在字典中保留。 有什么想法吗?
以下是代码:
Dictionary<String, String> Answers;
protected void Page_Load(object sender, EventArgs e)
{
Answers = (Dictionary<String, String>)ViewState["Answers"];
ViewState["Answers"] = Answers;
}
protected void rdb_study_popul_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySamplepopulation"] = rdb_study_popul.SelectedValue.ToString();
Answers.Add("StudyPopulation", ViewState["StudySamplepopulation"].ToString());
}
现在,如果我转到下一部分,Answers
将为空。
非常感谢任何帮助。
我得到null引用错误对象引用未设置为对象的实例。
公共部分类 { 字典答案;
protected void Page_Load(object sender, EventArgs e)
{
Answers = ( Dictionary<String, String>)ViewState["Answers"];
}
protected void rdb_studysubj_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySubjectAnimal"] = rdb_studysubj.SelectedValue.ToString();
studysub_popul.Visible = true;
Answers.Add("StudySubjectAnimal", ViewState["StudySubjectAnimal"].ToString());
ViewState["Answers"] = Answers;
}
答案 0 :(得分:1)
您无需更新页面加载中的ViewState
,因为它尚未更改,因此请删除ViewState
中Page_Load
的分配,然后执行此操作:
protected void Page_Load(object sender, EventArgs e)
{
// Only read the value from ViewState, do not update it here
Answers = (Dictionary<String, String>)ViewState["Answers"];
}
现在在您的事件处理程序中,当您完成添加到Answers
后,您应该更新ViewState
值,如下所示:
protected void rdb_study_popul_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["StudySamplepopulation"] = rdb_study_popul.SelectedValue.ToString();
Answers.Add("StudyPopulation", ViewState["StudySamplepopulation"].ToString());
// Now that you are done altering the Answers, save the updated value to ViewState
ViewState["Answers"] = Answers;
}
更新:
您需要检查ViewState
是否为空,如下所示:
Dictionary<String, String> Answers = new Dictionary<String, String>();
protected void Page_Load(object sender, EventArgs e)
{
// Is there anything in ViewState?
if (ViewState["Answers"] != null)
{
// Yes, but only read the value from ViewState, do not update it here
Answers = (Dictionary<String, String>)ViewState["Answers"];
}
}
注意:我更改了Answers
字典的声明以包括实例化它,因此它不会为空。