This is a migrated thread and some comments may be shown as answers.

Date is presented in JSON format

8 Answers 1544 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Dave
Top achievements
Rank 1
Dave asked on 01 Nov 2012, 08:11 PM
Hello. I'm using the Kendo grid, and most everything works well. However, when I set it to use Ajax for its datasource, it starts displaying the Date in JSON format (ex: /Date(1281538860000)/ ) in the grid.

If I change it back to a Server datasouce, it is displayed correctly as a DateTime.

Here is my grid:  (My date object is currently a nullable DateTime? field, not a property.)

@(Html.Kendo().Grid(Model)
    .Name("IssuesGrid")
    .Columns(column =>
        
            column.Bound(i => i.Id.Value).Title("Id"); 
            column.Bound(i => i.SubmitDate.Value).Title("Submitted");   
        })
    .Pageable()
    .Sortable()
    .Filterable()
    .Selectable(selectable => selectable.Mode(GridSelectionMode.Single))
    .Events(events => events.Change("rowSelected"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(15)
        .Read("GetIssuesAsync", "Issues")
        .Model(model => model.Id(i => i.Id))))

Ajax action:
public JsonResult GetIssuesAsync([DataSourceRequest]DataSourceRequest request)
{
    var issues = TempContext.GetIssues().ToDataSourceResult(request);
    return Json(issues);
}

I tried using the latest internal build but it doesn't seem to fix this.
Any help would be much appreciated. Thanks.

8 Answers, 1 is accepted

Sort by
0
Petur Subev
Telerik team
answered on 06 Nov 2012, 04:46 PM
Hello David,

I suspect that the column is bound to a nullable DateTime. If this is the case then you need to bind the column directly to that NullableField - because the Grid does not support binding to a non-flat model.
column.Bound(i => i.SubmitDate);


Kind Regards,
Petur Subev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Dave
Top achievements
Rank 1
answered on 20 Nov 2012, 08:35 PM
You were right - I created a ViewModel with a non-nullable DateTime for the date, and it worked fine after that.

That is, until I implemented functionality to refresh the grid from an AJAX datasource.

When the user clicks a search button, it fires some javascript:
function refreshGrid(e) {
    $.ajax({
        url: $(e).attr('data-url'),
        type: 'POST',
        data: $(e.form).serializeArray(),
        success: function (result) {
            var grid = $('#issuesGrid').data('kendoGrid');
            grid.dataSource.data(result);
            grid.refresh();
        }
    });
}
It's calling this method in the controller, which returns the JSON:

[HttpPost]
public JsonResult Search(ExistingIssuesSearchViewModel model)
{
    model.AddCriteria(IssueRepository.SearchCriteria);
    var issues = IssueRepository.GetIssues(model.FinalSearchValues);
    var datasource = Mapper.Map<List<Issue>, List<IssueViewModel>>(issues);
    return Json(datasource);
}
It's returning JSON of the same exact type that I use for the initial datasource. ( List<IssueViewModel> )

It populates and refreshes the grid fine, except now it shows the date in JSON format again!

/Date(1353440438000)/

This is from a standard, non-nullable DateTime property.

Any ideas on how to fix this would be greatly appreciated!
0
Petur Subev
Telerik team
answered on 21 Nov 2012, 07:02 AM
Hello David,

When using the mvc wrappers you need to add the kendo.aspnetmvc.min.js script to your pages, could you check if you missed it? Also you need to return DataSourceResult JSON object from your controller just like shown in our demos.

public ActionResult EditingInline_Read([DataSourceRequest] DataSourceRequest request)
{
    return Json(SessionProductRepository.All().ToDataSourceResult(request));
}


Kind Regards,
Petur Subev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Hatton Point
Top achievements
Rank 1
answered on 27 Jan 2013, 11:22 PM
Having the same issue as David's second. I'm binding a new dataSource to the Grid in javascript. I do not have an initial request object

[DataSourceRequest]DataSourceRequest request

How then do I return a properly formatted DataSource without having an initial DataSourceRequest or better yet how do I simply format date data correctly in the case of a generic Json object response?

I've tried creating an empty new DataSourceRequest() which formats the data different than a generic Json response, but the same issue occurs.

Controller (sending data):
return Json(FileUploadModel.GetByUploadGroupId(uploadGroupId).ToDataSourceResult(new DataSourceRequest()));
Script (receiving data):
var grid = $("#dasFilesGrid").data("kendoGrid");
grid.dataSource.data(e.response.Data);

Alternative using generic Json...

Controller:
return Json(FileUploadModel.GetByUploadGroupId(uploadGroupId));
Script:
grid.dataSource.data(e.response);
Grid:
@(Html.Kendo().Grid(Model)
    .Name("dasFilesGrid")
    .HtmlAttributes( new { @class = "edit-inline" })
    .Columns(columns =>
    {
        columns.Bound(m => m.FileUploadRawFileName);
        columns.Bound(m => m.FileCreatedDate)
            .EditorTemplateName("Date");
        columns.Bound(m => m.IsProcessed).ClientTemplate(
            "<input class='check-box' type='checkbox' disabled value='#= IsProcessed #' " +
                "# if (IsProcessed) { #" +
                    "checked='checked'" +
                "# } #" +
            "/>").Title("Upload ?");
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model =>
        {
            model.Id(e => e.FileUploadRawId);
            model.Field(e => e.FileUploadRawFileName).Editable(false);
        })
    )
)

In both cases, the date is formatted as /Date(1359328632830)/ in the Grid.
0
Erick
Top achievements
Rank 1
answered on 29 Jan 2013, 08:01 PM
I have the same issue but with different background:
My model is:
public class GraphValueModel
{
    public DateTime AxisXValue { get; set; }
    public string SerieName { get; set; }
    public object IndexValue { get; set; }
    public string Color { get; set; }
    public string ColumnOrGroupName { get; set; }
}
And in my Action(simplified) I have:
public ActionResult DataForEvo(string seriename, string category)
{
    return Json(GetDataForEvo(seriename));
}
The declaration with razor of my Kendo Chart is:

@(Html.Kendo().Chart(Model)
.Name("subchart")
.Title(title => title.Position(ChartTitlePosition.Top).Text("Clientes Activos: Vinculación"))
.Legend(legend => legend.Position(ChartLegendPosition.Top))
.DataSource(datasource => datasource
.Read(read => read.Action("DataForEvo", "Home", new { seriename = "Default", category = "Default" }))
.Group(group => group.Add(model => model.ColumnOrGroupName))
.Sort(sort => sort.Add(model => model.AxisXValue).Ascending())
)
  .Series(series =>
{
series.Line(model => model.IndexValue)
                    .Name("BAREVO").
                    GroupNameTemplate("#= group.value #");
            })
.Legend(legend => legend.Position(ChartLegendPosition.Bottom))
.ValueAxis(axis => axis.Numeric().Labels(labels => labels.Skip(2).Step(2)))
        .CategoryAxis(axis => axis
            .Categories(model => model.AxisXValue)
            .Labels(labels => labels.Format("MMM")))
)
And the first time, getting data with Json(GetDataForEvo(seriename)) works fine, everything.

Here is an image:
http://s20.postimage.org/imwatdq7x/Two_Graph.png

Now to obtain new data(at a click on the any serie of the graphic at the bottom) I use ajax:
function onSeriesClick(e) {
    var serieName = e.series.name;
    var serieCategory = e.category;
 
    $.ajax(
    {
        type: "POST",
        url: "DataForEvo",
        data: { seriename: serieName, category : serieCategory },
        success: function (data) {
        var chart = $("#subchart").data("kendoChart");
        chart.dataSource.data(data);
        //chart.refresh();
        },
        dataType: "json"
        });
}
Then all categories "AxisXValue" appears like /Date(1353440438000)/'.
One way how I solve this, is adding a foreach before add the new data to the chart:
var chart = $("#subchart").data("kendoChart");
$.each(data, function (i, obj) {
    obj.AxisXValue = new Date(parseInt(obj.AxisXValue.replace("/Date(", "").replace(")/", ""), 10));
});
 
chart.dataSource.data(data);
//chart.refresh();
If I use chart.refresh, the categories gonna will append to the last categories and born a new issue.

I know that exist issues, between the Json serializer of MVC and what expected  to get jquery, but the first time worked.
What's the right approach to solve this?

Many Thanks.
0
Petur Subev
Telerik team
answered on 30 Jan 2013, 02:16 PM
Hello Erick,

You are binding the new collection via the data method of the dataSource when your ajax request completes, however the dates are automatically parsed. You need to manually itarate through the items of the collection and parse these date fields. You can use the kendo.parseDate to do so.

Of course if you use the dataSource.read method you wont need to parse them. Why don't you use the dataSource.read method instead of the manual $.ajax request? You can event send additional parameters like this
$('#subchar').data().kendoChart.dataSource.read({foo:'bar'});



Kind regards,
Petur Subev
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
Hatton Point
Top achievements
Rank 1
answered on 30 Jan 2013, 10:34 PM
This latest example ultimately worked for me. Instead of trying to pass an ajax response of the entire grid data, I simply returned the datakey needed to rebind the grid and sent that to the read action in the grid. I also disabled the grid from autobinding - AutoBind(false)

Javascript Success Function (after upload):
$('#dasFilesGrid').data().kendoGrid.dataSource.read({ fileUploadGroupId: parseInt(e.response[0]) });

My grid now looks like standard example grid so I won't copy it all in here.

Controller:
public ActionResult UploadDas_Read([DataSourceRequest] DataSourceRequest request, int fileUploadGroupId)
{
    return Json(FileUploadModel.GetByFileUploadGroupId(fileUploadGroupId).ToDataSourceResult(request));
}
0
Brian
Top achievements
Rank 1
answered on 14 Feb 2013, 05:49 AM
I got this working using a ClientTemplate. In my case, I used moment.js (a 5.5k date library) to parse the JSON for me. 


        @(Html.Kendo().Grid(Model.Alerts)
            .Name("Grid")
            .Columns(columns =>
                {
                    columns.Bound(a => a.AlertID).Groupable(false).Hidden(!User.IsInRole("developer"));
                    columns.Bound(a => a.RIN).Title("RIN");
                    columns.Bound(a => a.FirstName).Title("First Name");
                    columns.Bound(a => a.Text).Title("Alert");
                    columns.Bound(a => a.CreatedTimestamp).Title("Timestamp").ClientTemplate("#= moment(CreatedTimestamp).format('LLLL') #");
                    columns.Bound(a => a.AlertID).ClientTemplate(string.Format("<a href='{0}?id=#= AlertID #'>select</a>", Url.Action("Edit")))
                                                       .Title("").Width(90).Sortable(false).Groupable(false).Filterable(false);
                })
            .DataSource(dataSource => dataSource
                .Ajax()
                .Read(read => read.Action("Grid_Read", "Home"))
            )
            .Sortable()
            .Groupable()
            .Filterable()
        )

Sorting works as expected. In this case, the LLLL format displays dates like this: Friday, January 1 2010 12:00 AM
Tags
Grid
Asked by
Dave
Top achievements
Rank 1
Answers by
Petur Subev
Telerik team
Dave
Top achievements
Rank 1
Hatton Point
Top achievements
Rank 1
Erick
Top achievements
Rank 1
Brian
Top achievements
Rank 1
Share this question
or