In this article I will explain with an example, how to solve the problem of ASP.Net Label value assigned in Client Side not appearing in PostBack.
ASP.Net Label controls do not send values to server and hence their value is lost on PostBack when set on Client Side.
To solve this issue we need to make use of Hidden Field which sends the Client Side modified value to server which can be later retrieved on PostBack in ASP.Net.
HTML Markup
The HTML Markup consists of an ASP.Net Label, a Hidden Field and a Button.
<asp:Label ID = "lblName" Text="Name" runat="server" />
<asp:HiddenField ID = "hfName" runat = "server" />
<br />
<br />
<asp:Button Text="Set Name" runat="server" OnClientClick = "SetName()" />
Setting value of Label on Client Side using JavaScript
The following JavaScript function is called when the Button is clicked. It first sets the value of the Label on client side using JavaScript.
Then the Label’s value is set in the Hidden Field.
<script type="text/javascript">
function SetName() {
var label = document.getElementById("<%=lblName.ClientID %>");
//Set the value of Label.
label.innerHTML = "Mudassar Khan";
//Set the value of Label in Hidden Field.
document.getElementById("<%=hfName.ClientID %>").value = label.innerHTML;
}
</script>
Fetching the value of Label set on ClientSide on PostBack in ASP.Net
Inside the Page Load event of the ASP.Net Page, the value of the Hidden Field set using JavaScript is fetched from the Request.Form collection using the UniqueID property.
The fetched value is again set to the Label control, this makes the Label retain its value on PostBack.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblName.Text = Request.Form[hfName.UniqueID];
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Me.IsPostBack Then
lblName.Text = Request.Form(hfName.UniqueID)
End If
End Sub
Screenshot
Label’s value is fetched using Hidden Field
Downloads