Display the current date in an ASP.NET label with C# and JS

lmhrpr picture lmhrpr · May 24, 2011 · Viewed 21.4k times · Source

I'm trying to display the current date in an ASP.NET label using JavaScript and C#. Here's what I have:

C#:

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScript", "GetDate()", true);
}

JS:

<script type="text/javascript">
    function GetDate() 
    {
        var dt = new Date();
        var element = document.getElementById("MainContent_FormView1_Label1");

        element.text = dt.toDateString();
    }
</script>

ASP.NET:

<asp:Label ID="Label1" runat="server" Text='<%# Bind("Date", "{0:d}") %>'></asp:Label>

Can anyone see where I'm going wrong? Also, can the JS be run when the page loads without using the C# Page_Load method? I picked up the RegisterStartupScript elsewhere but I don't really understand it.

Thanks, Liam

Answer

Geoff Appleford picture Geoff Appleford · May 24, 2011

Try using element.innerText = dt.toDateString(); instead.

Also, you don't need to use RegisterStartupScript. You can just call the getDate() function in the onLoad event.

<script type="text/javascript">

    window.onload = function(){
        getDate();
    };

    function getDate() 
    {
        var dt = new Date();
        var element = document.getElementById("MainContent_FormView1_Label1");

        element.text = dt.toDateString();
    }
</script>

However, you might want to read this SO thread for best practice in using window.onload, or consider using a framework such as jQuery and its document.ready