将日期字符串从C#控制器传递到Javascript函数正在改变字符串

时间:2013-08-28 17:56:56

标签: javascript asp.net-mvc

我遇到的问题是我的控制器将ViewData传递给视图,然后由javascript函数使用。 ViewData是格式化为字符串的日期。然而,一旦传入Javascript,字符串变成'0.021978021978021976'而不是'mm / dd / yy'fomrat。什么会导致这个? 以下是控制器中生成此视图数据的代码。

        string dateString;
        string cultureConfigKey = System.Configuration.ConfigurationManager.AppSettings["InstanceCulture"];
        DateTime? lastEntryDate = null;
        DataSet dSet = DataHelper.Measurements_GetLastMeasurement(userSession.UserIDNative);                
        foreach (DataRow dr in dSet.Tables[0].Rows)
        {
            lastEntryDate = (DateTime?)dr["When"];                                 
        }

        // format date based on culture and convert it to string
        if (cultureConfigKey == "en" )
        {                
            ViewData["DateString"] = dateString = String.Format("{0:MM/dd/yy}", lastEntryDate);
        }

在视图中我引用了ViewData,如下所示

        @
        {
            var dateString = ViewData["DateString"];
            // calling @dateString in this point shows the string in proper format
        }

        // further down in the view I pass the dateString into the following function which generates some markup that is supposed to prinout out this date string with in it. 
        buildNotification(@dateString);

        // the above function is built in an outside .js file here is its declaration 
        function buildNotification(dateString){
            $('.stats-chartsView').before(
            '<div class="noData-popup">' +
                '<p class="noData-Img"></p>' +
                '<p class="no-data alert">' + CHART_DATA_NOTIFICATION + '<span>'+ dateString +'</span></p>' +
            '</div>'
            );
        }

        Thanks!

1 个答案:

答案 0 :(得分:2)

可能是因为您没有在JS函数中使用引号传递此参数并将其视为字符串。

buildNotification(@dateString);

应该是

buildNotification('@dateString');

你的JS函数正在看到08/04/2013,并且最有可能对这三个整数进行长期划分。