ClosDesign ClosDesign - 1 year ago 209
C# Question

Razor/C# date to Javascript

I have a Razor/C# date coming from a controller I am calling from jQuery AJAX. The controller triggers and I am pulling it back through HttpContext.Current.Session in my View.

I am getting a date back when I debug the View and the Razor, BUT the issue is I keep getting date to format correctly in the Javascript. I keep trying to console out the output and it keeps giving me an error:
"Uncaught SyntaxError: missing ) after argument list"

The output in Chrome's Developer window is:
Session Date Issue

You can see that for some reason teh date is either not converting to a string properly or there is some sort of formatting happening that I am just not seeing or understanding. Any help is appreciated.

My JS and Razor is below:

function UpdateShowTimeList() {
var dateFromHubTimeList = DateTime.MinValue;
var objTimeList = HttpContext.Current.Session["CalendarSelectedDate"];

if(objTimeList != null)
dateFromHubTimeList = Convert.ToDateTime(objTimeList);


//Keep getting error on this line and have NO idea why
console.log("Session Selected Date Show Time List: " + @dateFromHubTimeList.ToString("dd/MM/yyyy HH:mm"));

//jQuery AJAX is here and is working.

Answer Source

You can use the following code in your console.log:

'@dateFromHubTimeList.ToString("dd/MM/yyyy HH:mm")'

Note: I put single quotes around my Razor code to make its result as js string.


console.log("Session Selected Date Show Time List: " +  
            '@dateFromHubTimeList.ToString("dd/MM/yyyy HH:mm")');

Also you have another options for different cases

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download