asp.net 中 DateTime 的 Javascript 序列化没有给出 javascript 日期对象? [英] Javascript serialization of DateTime in asp.net is not giving a javascript date object?

查看:19
本文介绍了asp.net 中 DateTime 的 Javascript 序列化没有给出 javascript 日期对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 .Net 中将 DateTime 解析为 json 时,它返回一个字符串(即 "/Date(1249335194272)/").如何让它返回一个不包含在字符串中的 js Date 对象构造函数?

When I parse a DateTime to json in .Net it returns a string (i.e. "/Date(1249335194272)/"). How do I make it return a js Date object constructor not wrap in a string?

// js server code
var dteNow = <%= jsonDateNow %>;


// js rendered code
var dteNow = "/Date(1249335477787)/";


// C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace testing{
    public partial class iTaxPrep : System.Web.UI.Page
    {
        protected string jsonDateNow;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                jsonDateNow = new JavaScriptSerializer().Serialize(DateTime.Now);

            }
        }
    }
}

推荐答案

这似乎有效(感谢 Chris S 的想法).在 C# 中进行替换以从日期对象周围移除字符串包装器;

This seems to work (Thanks Chris S for the idea). In the C# do a replace to remove the string wrapper from around the date object;

    using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.Script.Serialization;
        using System.Web.Script.Services;
        using System.Web.Services;
        using System.Web.UI.WebControls;

        namespace test
        {
            [ScriptService]
            public partial class testing: System.Web.UI.Page
            {
                protected string strCaseID;
                protected string jsonCase;

                protected void Page_Load(object sender, EventArgs e)
                {
                    if (!IsPostBack)
                    {
                        strCaseID =Tools.GetQueryObject("id");
                        // get a complex object with dates, string, arrays etc.
                        jsonESHACase = new JavaScriptSerializer().Serialize(objCase.Get(strCaseID ))
                            .Replace(""\/Date(", "new Date(").Replace(")\/"", ")");
                    }
                }
            }
        }

..并且在删除引号并将新前缀添加到 Date 之后,这个 js 现在可以工作了.万岁!

..and after removing the quotes and adding the new prefix to Date this js now works. Hooray!

testCase= <%= jsonESHACase %>;
    if (testCase) {
        document.write(testCase["ClosingDate"].format("MM dd yyyy"));
    }

这篇关于asp.net 中 DateTime 的 Javascript 序列化没有给出 javascript 日期对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆