ASP .NET向导控件和视图状态

时间:2013-07-18 01:10:57

标签: asp.net controls viewstate wizard

我有一个包含3个向导步骤的表单,当我单击按钮动态添加文本框时,工作正常,但是当我转到下一步并单击添加以添加更多文本框时,它会自动添加如果我一直点击它,那么前面步骤中的所有文本框都会继续添加。

我如何防止这种情况发生。

私人List ControlsList     {         得到         {             if(ViewState [“controls”] == null)             {                 ViewState [“controls”] = new List();             }             return(List)ViewState [“controls”];         }     }

private int NextID
{
    get
    {
        return ControlsList.Count + 1;
    }
}


protected override void LoadViewState(object savedState)
{

    string section = Wizard1.ActiveStep.ID;
    int sectionNum = Wizard1.ActiveStepIndex;

    var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;

    base.LoadViewState(savedState);

    int count = 0;
    foreach (string txtID in ControlsList)
    {
        if (count == 0)
        {
            control.Controls.Add(new LiteralControl("<tr>"));
        }
        TextBox txt = new TextBox();
        control.Controls.Add(new LiteralControl("<td>"));
        txt.ID = txtID;
        control.Controls.Add(txt);
        control.Controls.Add(new LiteralControl("</td>"));

        count = count + 1;
        if (count == 3)
        {
            control.Controls.Add(new LiteralControl("</tr>"));
            count = 0;
        }

    }
}


protected void AddControlButton_Click(object sender, EventArgs e)
{


    string section = Wizard1.ActiveStep.ID;
    int sectionNum = Wizard1.ActiveStepIndex;

    var control = Wizard1.ActiveStep.FindControl("Place" + sectionNum) as PlaceHolder;

    TextBox txt1 = new TextBox();
    TextBox txt2 = new TextBox();
    TextBox txt3 = new TextBox();


    txt1.ID = section.ToString() + "Size" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt1);
    control.Controls.Add(new LiteralControl("</td>"));
    ControlsList.Add(txt1.ID);

    txt2.ID = section.ToString() + "Description" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt2);
    control.Controls.Add(new LiteralControl("</td>"));
    ControlsList.Add(txt2.ID);

    txt3.ID = section.ToString() + "Quantity" + NextID.ToString();
    control.Controls.Add(new LiteralControl("<td>"));
    control.Controls.Add(txt3);
    control.Controls.Add(new LiteralControl("</td></tr>"));
    ControlsList.Add(txt3.ID);

}

1 个答案:

答案 0 :(得分:0)

您将所有动态文本框存储在ViewState中,然后ControlsList属性getter在构建文本框时返回整个列表。

我的建议是使用Session缓存而不是ViewState,因为它允许您区分文本框控件和每个向导步骤,如下所示:

Session["WizardStep1"] = listOfTextBoxesFromStep1;
Session["WizardStep2"] = listOfTextBoxesFromStep2;
Session["WizardStep3"] = listOfTextBoxesFromStep3;