Asp – UpdatePanel and Labels

asp.netasp.net-ajaxnetupdatepanel

I have an update panel with some controls in it. for example, I have a label, a textbox and a button to postback.

My label text is retrieved from the resource file, therefore, during page load I do the following

Page_Load()
{
    If(!isPostBack)
    {
        Label.Text = //Resource value;
    }    
}

Problem is, after posting back via the button click trigger, the label's text disappeared, as I assume the resource must be set again?

Any advice on getting rid of this redundant label postbacks? Because I have multiple controls, its hard to wrap all textboxes in one update panel etc…

Cheers

Best Answer

Label text values are maintained in the viewstate unless you have manually turned of viewstate for the label or a parent control. You shouldn't have to re-assign the label's text if the viewstate is enabled.

If you don't want the viewstate to be used but you are assigning the value dynamically from a resource then you will need to set the label's text property manually each time. The page being posted back has no knowledge of label values that are changed at runtime unless it is maintain in the viewstate.

ViewState produced for a control is heavy as it also stores other attributes of the label control. If nothing other than the value is changing, you might want to consider just storing the value in the ViewState object and turning off viewstate for the label controls and doing the wiring up manually on each postback.

// Store it
ViewState["YourLabel"] = "Text you want to store in the label.";

// On postback make sure you are assigning it
YourLabel.Text = Convert.ToString(ViewState["YourLabel"]);

I don't think you will find an automatic way of doing this. You could maybe write a helper function to do it automatically each time there is a postback by iterating through the items in the ViewState and assuming you have named the key the same as your controls, do a search for any label controls with the key's name and assign the text automatically based on the value stored for that key. I have never actually tried this but it probably would work at the expense of a little speed.