Note that there are some explanatory texts on larger screens.

plurals
  1. POIn an MVC 3 Application, how do I do a simple AJAX/JSON round trip of DateTimes and TimeSpans?
    primarykey
    data
    text
    <p>Given a simple round tripping scenario, how can I return JSON data to a browser and then accept updates from the browser via JSON that ModelBinds to a type w/ 3 properties: Int32, DateTime, TimeSpan?</p> <p>Server Code (Controller)</p> <pre><code> 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); } </code></pre> <p>Errors from Immediate Window</p> <pre><code>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 </code></pre> <p>Client Code (getData and changeData are bound to 2 different buttons)</p> <pre><code>&lt;script type='text/javascript'&gt; 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); } &lt;/script&gt; &lt;body&gt; &lt;button id="get" onclick="return(false);"&gt;get&lt;/button&gt; &lt;button id="post" onclick="return(false);"&gt;post&lt;/button&gt; &lt;/body&gt; </code></pre> <p><strong>Update March 2012</strong></p> <p>Looks like the upcoming <a href="http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx" rel="nofollow">Microsoft WebAPI will serialize to ISO8601</a> thanks to Scott Hanselman and <a href="https://github.com/JamesNK/Newtonsoft.Json/commit/fd760e33898cc6b3badaf4a8b77a466139b87fac" rel="nofollow">James Newton-King</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload