1. #1
    Sencha User
    Join Date
    Jun 2011
    Posts
    3
    Vote Rating
    0
    timjones is on a distinguished road

      0  

    Default Issues with MS AJAX serialized dates in JSON writer for Rest proxy

    Issues with MS AJAX serialized dates in JSON writer for Rest proxy


    I'm noticing some inconsistencies with how the JSON writer is serializing date fields in my models when transferring them to my web server. It appears that deserializing the data into a store works just fine, so it's only an outgoing issue.

    First, the codes....

    ASP.NET MVC Controller
    Code:
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using MvcApplication1.Models;
    
    namespace MvcApplication1.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                var user = new UserViewModel
                               {
                                   Id = 1,
                                   Name = "Billy Bob",
                                   HireDate = DateTime.Now.AddYears(-1),
                                   Orders = new List<OrderViewModel>
                                                {
                                                    new OrderViewModel {Id = 111, OrderDate = DateTime.Now.AddMonths(-1)},
                                                    new OrderViewModel {Id = 222, OrderDate = DateTime.Now}
                                                }
                               };
    
                return View(user);
            }
    
            [HttpPost]
            public ActionResult Save(UserViewModel user)
            {            
                return Json(user);
            }
        }
    }
    ASP.NET MVC View
    Code:
    @model MvcApplication1.Models.UserViewModel
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>@ViewBag.Title</title>
        <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/ExtJs/resources/css/ext-all.css")" />
        <script src="@Url.Content("~/Scripts/ext-all.js")" type="text/javascript"></script>
        <script type="text/javascript">
            Ext.require(['*']);
    
            Ext.define('User',
    	    {
    	        extend: 'Ext.data.Model',
    	        fields: ['Id', 'Name', { name: 'HireDate', type: 'date', dateFormat: 'MS' }],
    	        hasMany: { model: 'Order', name: 'Orders' }
    	    });
    
            Ext.define('Order',
            {
                extend: 'Ext.data.Model',
                fields: ['Id', { name: 'OrderDate', type: 'date', dateFormat: 'MS' }],
                belongsTo: 'User'
            });
    
            var model = @Html.Raw(Json.Encode(Model));
    
            var orderStore = new Ext.data.Store({
                model: 'Order',            
                data: model.Orders
            });
    
            var userStore = new Ext.data.Store({			
    			model: 'User',
    			proxy: {
    				type: 'rest',
    				url: '/Home/Save'
                    ,
                    writer: new Ext.data.JsonWriter({
                                getRecordData: function(record) { return record.data; }
                            })
    			}            
    		});
    
            var ordersGrid = Ext.create('Ext.grid.Panel',
            {
    			store: orderStore,			
    			columns: [
    				{
                        text: 'Id'
                        , flex: 30
                        , dataIndex: 'Id' 
                    },
                    {
                        text: 'Date'
                        , flex: 30
                        , dataIndex: 'OrderDate'
                        , editor: { xtype: 'datefield', 
                                    allowBlank: false}
                    }],			
    			selType: 'rowmodel',
                plugins: Ext.create('Ext.grid.plugin.RowEditing', {clicksToEdit: 1}),
                height: 200,
                minHeight: 200
            });
    
            var userForm = Ext.create('Ext.form.Panel', {
                url: '/Home/Save',
    			bodyStyle: 'padding:5px',
    			width: 350,
    			items: [
                    {
    					fieldLabel: 'Name',
                        xtype: 'textfield',
    					allowBlank: false,
    					name: 'Name',
    					value: model.Name
    				},
                    ordersGrid
                    ],
                buttons: [
    					{
    						text: 'Save',
    						handler: function()
                            {
                                userStore.add(model);
                                userStore.sync();
    						}
    					}]
            }); // end Create Form Panel
    
            Ext.onReady(function () {
                window.mainConsole = Ext.create('Ext.container.Viewport', {
                    layout: 'border',
                    renderTo: Ext.getBody(),                    
                    items: [{
                        region: 'center',
                        items: userForm
                        }]
                });            
            });
    </script>
    </head>
    <body>
    </body>
    </html>
    When I click Save on the form, the original model is simply being added to the user store and sync() is called which uses the rest proxy. I had to add to override the proxy's writer in order to include the user model's associations in the serialized data.

    The resulting JSON sent back to my controller is:
    {"Id":1, "Name":"Billy Bob", "HireDate":"2010-06-22T13:51:17", "Orders":[{"Id":111, "OrderDate":"/Date(1306090277970)/"}, {"Id":222, "OrderDate":"/Date(1308768677970)/"}]}
    1. Why is the OrderDate value missing the back slashes for the MS AJAX format? This is an invalid date format. It should have been {"Id":1, "Name":"Billy Bob", "HireDate":"\/Date(1277232677970)\/", "Orders":[{"Id":111, "OrderDate":"\/Date(1306090277970)\/"}, {"Id":222,"OrderDate":"\/Date(1308768677970)\/"}]};

    2. Why is HireDate not in the same format as OrderDate in the Orders collection? Both are defined with the same format, and both are properly loaded from MVC into the model.

    Thanks!

  2. #2
    Touch Premium Member
    Join Date
    Aug 2010
    Posts
    21
    Vote Rating
    0
    MaxQ is on a distinguished road

      0  

    Default


    I have the same problem using REST talking to a Java Spring server.

    The server encode dates in unix timestamp format. This is decoded correctly by the model when the field is defined like this:

    Code:
    {name: 'scheduledDate', type: 'date', dateFormat: 'time'},
    It is then displayed correctly when the form field is defined like this:
    Code:
    {
                        xtype : 'datefield',
                        fieldLabel : 'Tid',
                        name: 'scheduledDate',
                        anchor : '100%',
                        format: 'd.m.Y H:i'
    }
    But when I save the model, the PUT to the server use this date format: "2011-09-20T14:00:00".

    To me, the logical thing would be that the model translated the field back to time stamp due to the date format 'time'. Why is it not? How do I set which date format to use when PUT'ing ans POST'ing back?
    Last edited by MaxQ; 29 Sep 2011 at 7:27 AM. Reason: Added code tags

  3. #3
    Sencha User
    Join Date
    Jun 2011
    Posts
    3
    Vote Rating
    0
    timjones is on a distinguished road

      0  

    Default


    But when I save the model, the PUT to the server use this date format: "2011-09-20T14:00:00".
    how are you saving it? If it's a native form post, I don't know if you can customize the format that much. If you're using the model's proxy, then it should post back using the format you defined in your model definition. At least that's the behavior I've noticed.

  4. #4
    Touch Premium Member
    Join Date
    Aug 2010
    Posts
    21
    Vote Rating
    0
    MaxQ is on a distinguished road

      0  

    Default


    I use the models proxy, just calling .save() on the model.

    I resolved the problem by doing this on the top of my app.js file:

    Code:
    Ext.JSON.encodeDate = function(d) {
        return parseInt(Ext.Date.format(d, 'U'))*1000;
    };
    I find it strange that the proxy or model don't handle the date format in both directions when using the .save() method on the model. The normal behavior from a REST controller is that you GET, PUT and POST using the same formats.

  5. #5
    Sencha User
    Join Date
    Oct 2013
    Posts
    6
    Vote Rating
    0
    vanduc1102 is on a distinguished road

      0  

    Default


    my solution is:
    In Model
    Code:
    Ext.define('MyApp.model.ScheduleCollectionModel', {
        extend: 'Ext.data.Model',
    
    
        requires: [
            'Ext.data.Field'
        ],
    
    
        config: {
            fields: [
                {
                    name: 'schedulebeginTime'
                },
                {
                    convert: function(v, rec) {
                        return new Date(v);
                    },
                    name: 'scheduleDate',
                    type: 'date'
                },
                {
                    name: 'scheduleendTime'
                },
                {
                    name: 'houseNr'
                }
    }
    In tpl of ListView
    Code:
    <div>scheduleDate:date("m.d.Y")}</div>

Thread Participants: 2