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 :)
source to share
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 .
source to share
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";
source to share