Get value of Label set using JavaScript on Page Load in ASP.Net

Last Reply on May 02, 2018 12:08 AM By kalpesh

Posted on May 01, 2018 11:56 PM

I read Mudassar's article on that issue.

In his example the JavaScript is launched on a button clients click. In my case the javascript function is launched on pageload by 

Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowDate", "SetName()", true);

How can I retrieve the value assigned to the label/hidden field in this case?

Request.Form[hfName.UniqueID] is not working!

My function:

function SetName() {
    var dt = new Date();
    var label = document.getElementById("<%=LabelLocalTime1.ClientID %>");
    label.innerHTML = dt;
    document.getElementById("<%=hfName.ClientID %>").value = label.innerHTML;
Posted on May 02, 2018 12:08 AM

Because you are just calling SetName javascript fuction on page load but you are not posting back the page by ckicking any button so how can the Request.Form[hfName.UniqueID] will return the value.

Refer the below sample code for your reference here i just added one Link Button which dont have click event. On SetName javascipt fuction i just calling the LinkButton Click event so it will postback the page and return the HiddenField value from Request.Form[hfName.UniqueID].


<html xmlns="">
<head runat="server">
    <style type="text/css">
            font-family: Arial;
            font-size: 10pt;
    <script type="text/javascript" src=""></script>
    <form id="form1" runat="server">
    <asp:Label ID="lblName" Text="Name" runat="server" />
    <asp:HiddenField ID="hfName" runat="server" />
    <asp:LinkButton ID="lnkfake" runat="server"></asp:LinkButton>
    <br />
    <br />
    <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;


protected void Page_Load(object sender, EventArgs e)
    if (!this.IsPostBack)
        Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowDate", "SetName()", true);            
    if (this.IsPostBack)
        lblName.Text = Request.Form[hfName.UniqueID];


Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Page.ClientScript.RegisterStartupScript(Me.[GetType](), "ShowDate", "SetName()", True)
    End If

    If Me.IsPostBack Then
        lblName.Text = Request.Form(hfName.UniqueID)
    End If
End Sub