Ibraheem Mansour Ibraheem Mansour - 4 months ago 25
Javascript Question

Get ASP.NET label's text or value in JavaScript

I want to transfer a string of data from C# to JavaScript in ASP web forms. My approach is to set the data as a text for an ASP label in C# and then grab the label's text by ID in JS.

C# code (ascx.cs file):

List<Event> eventList;

protected void Page_Load(object sender, EventArgs e)
{
string message = string.Empty;
SPSite franasabank = new SPSite("http://lbshrptweb/sites/fransabank/");
SPWeb calendar = franasabank.OpenWeb();
SPList list = calendar.Lists["Fransabank Calendar"];
eventList = new List<Event>();
foreach (SPListItem oItem in list.Items)
{
// Access each item in the list...
DateTime startTime = (DateTime)oItem["Start Time"];
DateTime endTime = (DateTime)oItem["End Time"];
string status = (String)oItem["Status"];
string title = oItem.Title;
string description = (String)oItem["Description"];
Event calendar_event = new Event(startTime, endTime, status, title, description);
eventList.Add(calendar_event);
}
foreach (Event item in eventList)
{
message += item.Title + " " + item.Description + item.StartDate + "-" + item.EndDate + "-" + item.Status + "\n";
}

Label1.Text = message;
}


HTML snippet showing the Label (ascx file):

<div data-ng-app="Calendar">
<div data-ng-controller="CalendarController" id="mycontroller">
<div class="row " data-ng-init="Initialize()">
<asp:Label ID="Label1" runat="server" Text="Label" ></asp:Label>


JavaScript code:

<script>
var a = document.getElementById('<%= Label1.ClientID %>');
console.log(a);
</script>


I'm receiving the data as null in variable 'a'. I've tried

var a = document.getElementById('<%= Label1.ClientID %>').innerHTML;


but it is also null

Answer

Sounds like Javascript runs before the label is loaded

  1. Place the js after the <asp:Label> on the page. Preferably before </body>:

        <script>
            var a = document.getElementById('<%= Label1.ClientID %>');
            console.log(a);
        </script>
    </body>
    
  2. Alternatively you can surround the code block with jQuery $(document).ready():

    <script>
        $(document).ready(function () {
            var a = document.getElementById('<%= Label1.ClientID %>');
            console.log(a);
        });
    </script>