1

我有一个问题和答案页面,当某些问题被隐藏并且某些问题根据先前的答案变得可见时。最后我需要所有的答案。我正在尝试为此使用字典。我在每个控件的更改事件上添加一个带有键的答案。但是当我移动到下一部分时,没有一个答案被保存,因为我隐藏了前面的部分。

我正在尝试将其保存在视图状态中并添加值,以便我的值保留在字典中。有什么想法吗?

这是代码:

    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如果我转到下一部分,它将是空的。

任何帮助将不胜感激。


我收到空引用错误对象引用未设置为对象的实例。

公共部分类{字典答案;

    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;
        }
4

1 回答 1

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字典的声明更改为还包括实例化它,这样它就不会为空。

于 2013-08-12T17:17:17.170 回答