jquery - 在 MVC 3 应用程序中,如何执行 DateTimes 和 TimeSpans 的简单 AJAX/JSON 往返?

标签 jquery asp.net-mvc json asp.net-mvc-3

给定一个简单的往返场景,如何将 JSON 数据返回到浏览器,然后通过 ModelBinds 到具有 3 个属性的类型(Int32、DateTime、TimeSpan)的 JSON 接受来自浏览器的更新?

服务器代码( Controller )

    public class Product
    {
        public int Id { get; set; }
        public DateTime Start { get; set; }
        public TimeSpan Duration { get; set; }
    }

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult data()
    {
        return Json(
           new Product {
               Id = 1, Start = DateTime.Now, 
               Duration = TimeSpan.FromMinutes(30)}
           , JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public void data(Product product)
    {
        //product is not bound; modelbinder fails on DateTime and TimeSpan
        Console.WriteLine("Data: " + product);
    }

立即窗口中的错误

ModelState["Start"].Errors[0]
{System.Web.Mvc.ModelError}
    ErrorMessage: "The value '/Date(1302295231115)/' is not valid for Start."
    Exception: null

ModelState["Duration"].Errors[0]
{System.Web.Mvc.ModelError}
    ErrorMessage: "The Duration field is required."
    Exception: null

客户端代码(getData和changeData绑定(bind)到2个不同的按钮)

<script type='text/javascript'>
    var myData;
    function getData(event)
    {
        $.getJSON('/home/data', function (data)
        {
            myData=data;
            console.dir(data);                
        });
    }

    function changeData(event)
    {
        var postData = JSON.stringify(myData);

        $.ajax({
            url: '/home/data',
            type: "POST",
            data: postData,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function () {
                console.log('success!');
            },
            error: function () {
                console.log('fail!');
            }
            });
    }

    $(document).ready(function ()
    {
        $('#get').click(getData);
        $('#post').click(changeData);
    }
</script>

<body>
    <button id="get" onclick="return(false);">get</button>
    <button id="post" onclick="return(false);">post</button>
</body>

2012 年 3 月更新

看起来像是即将推出的Microsoft WebAPI will serialize to ISO8601感谢 Scott Hanselman 和 James Newton-King

最佳答案

处理日期的方式存在问题。 JavaScriptSerializer处理日期时使用以下格式: /Date(1302296382818)/ 不幸的是,在解析 GET JSON 响应时,这对 jQuery 没有什么意义,因此您在客户端无法获得真正的日期,而是字符串。因此,您需要无耻的黑客才能将此字符串转换为真实日期:

myData.Start = new Date(parseInt(data.Start.substr(6)));

这是黑客攻击的完整故事:

型号:

public class Product
{
    public int Id { get; set; }
    public DateTime Start { get; set; }
}

Controller :

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Data()
    {
        var product = new Product
        {
            Id = 1,
            Start = DateTime.Now,
        };
        return Json(product, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult Data(Product product)
    {
        return Json(product);
    }
}

查看:

<script type="text/javascript">
    var myData;

    function getData(event) {
        $.getJSON('/home/data', function (data) {
            myData = data;
            myData.Start = new Date(parseInt(data.Start.substr(6)));
        });
        return false;
    }

    function changeData(event)
    {
        var postData = JSON.stringify(myData);

        $.ajax({
            url: '/home/data',
            type: 'POST',
            data: postData,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                console.log(result);
            }
        });

        return false;
    }

    $(function () {
        $('#get').click(getData);
        $('#post').click(changeData);
    });
</script>

<button id="get">get</button>
<button id="post">post</button>

TimeSpan 案例留给读者作为练习,因为它将需要另一次无耻的黑客攻击,而我厌倦了黑客攻击:-)

关于jquery - 在 MVC 3 应用程序中,如何执行 DateTimes 和 TimeSpans 的简单 AJAX/JSON 往返?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5600510/

相关文章:

javascript - 等待执行完成再执行

javascript - 如果不存在 php,则在不同的文件夹中创建 txt 文件

javascript - 仅当两个输入都模糊时触发某些内容

c# - 将字符串读入 Json

javascript - 如何通过 jquery 获取 .find() 对象中的最后一个元素

c# - 存储可以循环编辑的列表?

asp.net-mvc - 与 ASP.NET MVC 集成的经典 ASP

javascript - 在 asp.net mvc 3 中引用自定义外部 javascript 文件

java - json 反序列化器到目标对象

javascript - For 循环和顺序超时