为什么ajax显示DateTime格式错误“/日期(1493818989603)/”?

时间:2017-05-03 13:52:56

标签: jquery ajax asp.net-mvc

我想将表单发送到 MVC控制器控制器返回DateTime 但显示此格式 /日期(1493818989603)/ 。我有一个简单的表单(输入和按钮)。

    [HttpPost]
    [DynamicCache(VaryByParam = "none")]
    public ActionResult DynamicCache(int duration)
    {
        var configuration = WebConfigurationManager.OpenWebConfiguration("~");
        configuration.AppSettings.Settings["Duration"].Value = duration.ToString();
        configuration.Save();

        System.Web.HttpRuntime.UnloadAppDomain();

        var timeNow = DateTime.Now;
        return Json(new { result = timeNow });

    }

====================================

<div class="container">
    <div class="form-horizontal">
        <div class="form-group ">
            <div class="col-sm-10 col-md-10 col-lg-10 col-sm-offset-1">
                <input type="number" class="form-control form-control input-lg" id="suplyNumber" placeholder="Enter number">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-10 col-md-10 col-lg-10 col-sm-offset-1">
                <button type="submit" id="btnSubmit" class="btn btn-default btn-lg btn-block">Submit</button>
            </div>
        </div>
    </div>
</div>
<hr />
<h1 class="col-lg-offset-5">Result</h1>
<div class="container">
    <div class="row">
        <div id="result">

        </div>
    </div>

</div>
<script>
    $(function () {
        $("#btnSubmit").click(function () {
            var duration = $("#suplyNumber").val();
            var dataJson = { "duration": duration };
            $.ajax({
                type: "POST",
                url: "/Home/DynamicCache",
                data: JSON.stringify(dataJson),
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    $("#result").html("Result: " + data.result);
                }
            });
        });
    });
</script>

1 个答案:

答案 0 :(得分:0)

我已添加此作为答案,以便您可以正确阅读。默认的.NET json序列化程序以以下格式返回日期:例如/日期(1493818989603)/

如果您定义原型函数,例如:

// .NET Date/String converter
if (!String.prototype.parseNETDate) {
    String.prototype.parseNETDate = function () {
        if (this.indexOf('-') == -1) {
            return new Date(parseInt(this.slice(6, 19)));
        } else {
            return new Date(parseInt(this.slice(6, 20)));
        }
    };
}

然后在你的对象上你可以做到:

var dateParsed = data.result.parseNETDate();

必须在调用之前定义函数。