In this article I will explain with an example, how to get value of Label set on client side using JavaScript on server side (code behind) in ASP.Net using C# and VB.Net.
Label controls do not send values to server and hence their value is lost on PostBack. To solve this issue we need to make use of Hidden Field which sends the JavaScript modified value to server.
 
 
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()" />
 
 
Change 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 using JavaScript on server side 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
Get value of Label set using JavaScript on Server Side in ASP.Net using C# and VB.Net
 
 
Downloads