How to pass C# variable to javascript variable?

Posted on 2008-11-05
Last Modified: 2013-12-17

In VC# code, it gets the current date time from system

protected System.DateTime CurDateTime;

protected string SysDateTime;

this.CurDateTime = System.DateTime.Now;

this.SysDateTime = this.CurDateTime.ToString("month dd, yyyy HH:mm:ss");

I have a javascript variable needs to get the SysDateTime value in aspx page.

var currenttime = <%= SysDateTime %>;

But, it cannot get it, how should I write it?

Question by:techques
    LVL 7

    Accepted Solution

    Instead of: var currenttime = <%= SysDateTime %>;

    Try: var currenttime = "<%= SysDateTime %>";
    LVL 25

    Assisted Solution

    by:Lee Savidge

    I would put the javascript in the codebehind and then build it that way. Then when the page is built server side, the script is generated and sent clientside ready populated. Take a look at

    Page.RegisterStartupScript and Page.RegisterClientScriptBlock both emit javascript to the client side but are built server side which means you have full control over it.



    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now