ASP.NET Best way to retain label.text value between postback with PageMethods

Cedric Aube picture Cedric Aube · Apr 1, 2009 · Viewed 16.6k times · Source

ASP.NET 2.0, PageMethods.

Good day,

I'm using ASP.NET AJAX PageMethods to dynamically change the text of a Label when a dropdownlist is changed on my page.

I know that the text of Labels are not retained between postbacks when they are changed on client-side, which is my case. I've heard that a solution is to keep the label content in a hidden field, then to set Label text from that field in Page_Load.

However, this solution does not seem really clean to me. Are there any other alternatives or best practices?

Thank you!


Just to clarify, I have a dropdownlist with people names. When the dropdownlist get changed, I want, in a label, to put the telephone of that person. However, I thought that doing a full postback was not really the best alternative, so I decided to get the telephone with a PageMethod, passing the Id of the item selected in the dropdownlist to retrieve the telephone, and the put it in the label.

However, since other controls cause a full postback, I lose the telephone on every postback. I know that putting it in a hidden field, then setting it back to the label in Page_Load when there is a full postback would work, but I was wordering if there was another solution. Since WebMethods are marked as static, I cannot write Label.text = person.Telephone; in them.

Answer

gsnerf picture gsnerf · Apr 1, 2009

As you seem to have ajax you could just do a partial postback, write the number to the label and into the viewstate, and in page_load write the value from the viewstate to the label.

In the DropDownList eventhandler:

string phone = <.. get phone number ...>;
myLabel.Text = phone;
ViewState["currentPhone"] = phone;

And on PageLoad:

myLabel.Text = (ViewState["currentPhone"] != null) ? (string)ViewState["currentPhone"] : string.Empty;

If you don't want to use Ajax you can define a HiddenInputField in your aspx file, fill the content with javascript and on Postback fill the label with the content. On aspx:

<asp:HiddenInputField runat="server" ID="myHiddenInput" />

on PageLoad:

myLabel.Text = myHiddenInput.Value;