Is there a way to maintain ASP.NET ViewState in a dynamically rendered HTML control?

I want to create a custom control that has a couple of controls <input type='checkbox' />

that I render in a Render method. Is it possible to keep the ViewState (like checked or not) on these controls?

There is a way to do this using the ASP.NET Server CheckBox control, adding them to the OnLoad event with this .Controls.Add (), and giving them the same IDs every time, but I don't want to do that :)

+1


source to share


3 answers


If you want the ViewState to be restored to a dynamic control, you must re-create that control before the load event. This means that this is the code in the handler Init

.



+2


source


When you create a control, first make sure you add it to the page and then set any properties for them. This is because in order for the ViewState manager to consider a control for a control, it must detect a change, and it can only detect a change after the control has been added to the Controls collection.

It is also important to set an explicit identifier . When the ViewState is saved and restored, the control ids must match.



Also make sure you create the controls at the right time (OnInit) in the page lifecycle .

+2


source


You can simply access the ViewState directly:

bool checked = (bool)(ViewState["ThisControlCheckState"] ?? false);
if (checked) {
    write("<input ... >");
}
else {
    write("<input ... >");
}

      

To save your user form form, you can do something like this in PostBack:

ViewState["ThisControlCheckState"] = request.Params["checkboxName"].ToString() == "1";

      

+1


source







All Articles