简体   繁体   中英

Unable to pass date from c# to javascript function

I'm dynamically building html table from c# code. Here is a portion of my code:

listHTML.Append("<td onClick='GoToHourlyReport("
    + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd")
    + ","
    + deptId
    + ");' align='center' valign='middle' class='graph_red_grid_text'>"
    + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd hh:mm:ss")
    + "</td>"
);

On onclick of the td I'm trying to pass a date to a JavaScript function.

onClick='GoToHourlyReport("
    + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd")
    + ","
    + deptId
    + ");' 

But when I pass a date like 2012-10-01 , I get a value 1999 inside JavaScript function all the time. Can any one throw some light about what I'm doing wrong?

Here is the js function

    function GoToHourlyReport(date, deptId) {
    window.location.href = "CallAverageHourlyReport_BW.aspx?Date=" + date + "&Queue=" + deptId;
}

View the page source, you will see your problem. You are missing quotes in the generated code.

In short you are doing

alert(2012-10-01);

not

alert("2012-10-01");

Add an escaped "

listHTML.Append("<td onClick='GoToHourlyReport(\"" + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd") + "\",\"" + deptId + "\");'...

You need to pass the date as a string, otherwise it gets interpreted as a number (2,010 minus 10 minus 1 = 1,999):

listHTML.Append("<td onClick=\"GoToHourlyReport('"
    + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd")
    + "',"
    + deptId
    + ");\" align='center' valign='middle' class='graph_red_grid_text'>"
    + Convert.ToDateTime(dr["IntervalStartTime"]).ToString("yyyy-MM-dd hh:mm:ss")
    + "</td>"
);

This should generate:

<td onclick="GoToHourlyReport('2010-10-01', 1)" ...>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM