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

grid TimeSpan [object Object] asp.net MVC

12 Answers 2127 Views
Date/Time Pickers
This is a migrated thread and some comments may be shown as answers.
Azmi
Top achievements
Rank 2
Azmi asked on 18 Apr 2016, 10:27 PM

Hey

I have problem with the grid his not showing createdTime  Why ? I so Tired for searching solution  plzz help me Im beginner  In  kendo and that my code :

View :
@(Html.Kendo().Grid<appfox.Models.Address>()
        .Name("grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.AddressLine1);
            columns.Bound(p => p.AddressLine2).Visible(false);
            columns.Bound(p => p.AddressPostalCode);
            columns.Bound(p => p.CreatedDate).Format("{0:dd-MM-yyyy}").EditorTemplateName("Date");
            columns.Bound(p => p.CreatedTime).Format("{0:HH:mm:ss}").EditorTemplateName("Date");
            columns.Command(command => command.Custom("ViewDetails").Click("showDetails")).Width(180);


        })
                   .Resizable(resize => resize.Columns(true))
                    .Reorderable(reorder => reorder.Columns(true))
        .HtmlAttributes(new { style = "height: 380px;" })
        .Scrollable()
        .Groupable()
            .Sortable()
            
        
        .Pageable(pageable => pageable
            .Refresh(true)
            .PageSizes(true)
            .ButtonCount(5))
        .DataSource(dataSource => dataSource
            .Ajax()
                   .Model(model =>
                    {
                        model.Field(x => x.AddressId).Editable(false);
                        model.Id(x => x.AddressId);


                    })
            .Read(read => read.Action("List", "Test"))
            
            )
 

)

@(Html.Kendo().Window().Name("Details")
    .Title("Customer Details")
    .Visible(false)
    .Modal(true)
    .Draggable(true)
        .LoadContentFrom("List", "Test")
    .Width(300))

_____________________________________________________________________________________

Class:

 public partial class Address
    {
        public int AddressId { get; set; }
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public Nullable<byte> AddressPostalCode { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
        public string TimeZone { get; set; }
        public string CreatedBy { get; set; }
        public System.DateTime CreatedDate { get; set; }
        public System.TimeSpan CreatedTime { get; set; }
        public string UpdatedBy { get; set; }
        public System.DateTime UpdatedDate { get; set; }
        public System.TimeSpan UpdatedTime { get; set; }
    }
}

 

Controller 

        public ActionResult Index1([DataSourceRequest]DataSourceRequest request)
        {
            List<Address> omList = new List<Address>();
            Address om = new Address();


            using (Test1Entities objContext = new Test1Entities())
            {
                var q = objContext.Address.ToList();
                omList = getOrders(q);

                DataSourceResult result = omList.ToDataSourceResult(request);
                return View(result);

                // return omList;
            }


        }

        private List<Address> getOrders(List<Address> olist)
        {
            List<Address> omList = new List<Address>();
            foreach (var ads in olist)
            {
                Address o = new Address();
               
                o.AddressLine1 = ads.AddressLine1;
                o.AddressLine2 = ads.AddressLine2;
                o.AddressPostalCode = ads.AddressPostalCode;
                o.City = ads.City;
                o.State = ads.State;
                o.Country = ads.Country;
                o.TimeZone = ads.TimeZone;
                o.CreatedBy = ads.CreatedBy;
                o.CreatedDate = ads.CreatedDate;
                omList.Add(o);
            }

            return omList;
        }

        public ActionResult List([DataSourceRequest]DataSourceRequest request)
        {
            List<Address> omList = new List<Address>();
            Address om = new Address();


            using (Test1Entities objContext = new Test1Entities())
            {
                var q = objContext.Address.ToList();
                omList = getOrders(q);

                DataSourceResult result = omList.ToDataSourceResult(request);
                return Json(result, JsonRequestBehavior.AllowGet);

                // return omList;
            }
        }

12 Answers, 1 is accepted

Sort by
0
Dimiter Topalov
Telerik team
answered on 20 Apr 2016, 02:55 PM
Hello Azmi,

[Object object] is rendered because the corresponding column is of complex type (struct), and cannot be serialized and rendered properly.

The easiest approach to solve the problem is simply to use the CreatedDate property, bind another column to it and format it to show the time only:

...
columns.Bound(p => p.CreatedDate).Format("{0:hh:mm:ss}").Title("Created Time").EditorTemplateName("Date");
...

Another option is to use the ClientTemplate() method.

Let me know if you need further assistance.

Regards,
Dimiter Topalov
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
AMF
Top achievements
Rank 2
answered on 06 Mar 2019, 01:09 PM

Hi Dimiter,

I'm having the same issue as Azmi, but the problem is, that I don't have a DateTime column or object with the same value. I've got a Time column in my SQL database. In the model i'm using a TimeSpan to store the data.

I've looked at the clienttemplate method, but the template "#= kendo.toString(" + col.Fieldname + ", '" + "HH:mm" + "')#" still displays [object Object]  

0
Alex Hajigeorgieva
Telerik team
answered on 08 Mar 2019, 11:55 AM
Hi,

The ASP.NET MVC TimeSpan struct is translated to an object on the client containing these properties:



This is the reason why the provided column template fails and produces the [object Object] output, as it is still an object. To cater for the timespan, and format it as desired, you may use the following:

columns.Bound(p => p.FieldName).ClientTemplate("#= kendo.format('{0:00}:{1:00}', FieldName.Hours, FieldName.Minutes) #");

https://docs.telerik.com/kendo-ui/api/javascript/kendo/methods/format

Also in case of editing, you may check the following project:

https://docs.telerik.com/aspnet-mvc/helpers/grid/how-to/editing/grid-timespan-editor


Kind Regards,
Alex Hajigeorgieva
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
AMF
Top achievements
Rank 2
answered on 18 Mar 2019, 10:51 AM
Thanks!
0
Curt
Top achievements
Rank 1
answered on 21 Oct 2019, 09:39 PM

Alex,

So I am using timespan in my grid and you suggestion works great there. However when sending the model to the Controller as Jason I get the following error: 

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.TimeSpan' because the type requires a JSON primitive value (e.g. string, number, boolean, null) to deserialize correctly.
To fix this error either change the JSON to a JSON primitive value (e.g. string, number, boolean, null) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'shft_beg_tm.Ticks', line 1, position 186.

Any help you could provide would be appreciated! Thanks so much!

Curt

0
Alex Hajigeorgieva
Telerik team
answered on 22 Oct 2019, 07:40 AM

Hi, Curt,

I have already replied to you in the private thread that you have submitted but I will post my response here as well.

To use the Kendo UI TimePicker as an editor and bind it to a timepicker type, we need:

  • a client-side custom binder that is able to bind the minutes, hours and seconds in the widget as they are separate fields as opposed to the Date object the widget expects
  • a server-side custom model binder registered in the Global.asax.cs

Runnable project is available here:

https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/grid/grid-timespan-editor

Kind Regards,
Alex Hajigeorgieva
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
William
Top achievements
Rank 1
answered on 04 Aug 2020, 06:03 PM

Hello,

 

Im having the same issue, tried your solution and still doesnt work; I'm currently using Kendo.MVC v2019.1.115.545

Im getting the following error in the front end: 

    Uncaught TypeError: Cannot read property 'eq' of undefined

Can you please review and see whats going on?

Btw, I'm able to display a read only field, but I need to be able to update it, below are the snippets i have:

This works (template / read only field):

columns.Template(@<text></text>).ClientTemplate("#=FormatTimeFromTimeSpan(data.ExecutionTime)#").Title("Execution Time").Width(150);

 

This doesn't work -- it throws a js error.

columns.Bound(p => p.ExecutionTime).ClientTemplate("#= kendo.format('{0:00}:{1:00}', ExecutionTime.Hours, ExecutionTime.Minutes) #");
0
Alex Hajigeorgieva
Telerik team
answered on 06 Aug 2020, 04:42 PM

Hello, William,

I downloaded and tested the project and it works well in my test. There are two approaches - one with a TimePicker and one with a Numeric:

The Timepicker editor requires you to implement a custom client side binder:

https://github.com/telerik/ui-for-aspnet-mvc-examples/blob/master/grid/grid-timespan-editor/GridTimeSpanEditor/Views/Home/TimePickerEditor.cshtml#L6-L40

And both require a server side Binder:

https://github.com/telerik/ui-for-aspnet-mvc-examples/blob/master/grid/grid-timespan-editor/GridTimeSpanEditor/Binders/TimeSpanModelBinder.cs

Do you have both of these steps implemented and which is your preferred way of editing?

I am attaching the project itself here so you can easily inspect it. In case of any difficulties, please modify the project to reproduce the error so we can provide you with specific guidance how to fix them.

Regards,
Alex Hajigeorgieva
Progress Telerik

0
William
Top achievements
Rank 1
answered on 11 Aug 2020, 01:07 PM

Hi Alex,

The problem seems to be with the field itself: the TimeSpan defined in my model is nullable:

 

 

public TimeSpan? Time2 { get; set; }

 

I modified your project and added a nullable Timespan to the model and the project crashes (attached). Could it be that there is a bug in the library and it doesnt know how to handle it?

 

Thanks in advance.

 

-- William

0
Alex Hajigeorgieva
Telerik team
answered on 13 Aug 2020, 03:40 PM

Hi, William,

A bug is considered a fault in existing functionality. In this scenario, there is not such thing as a TimeSpan editor and we are creating it using a NumericTextBox and a custom server binder.

We need to consider that in the case of a nullable TimeSpan, we are dealing with a different type and modify the editor accordingly. ASP.NET MVC does not find the properties for TimeSpan?.Hours as they are not valid in case the type is null, the framework requires you check that it HasValue first.

We can use the fact that the editor is bound on the client and instead of binding to the nested property of a nullable (Hours) for example which we are restricted by ASP.NET MVC, we can provide the matching name for the editor so Kendo can bind it to the property value on edit:

@model TimeSpan?

@Html.Kendo().IntegerTextBox().Name(ViewData.TemplateInfo.GetFullHtmlFieldName("") + ".Hours").HtmlAttributes(new { style = "width: 30px;" , id= ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Hours" }).Spinners(false) :
@Html.Kendo().IntegerTextBox().Name(ViewData.TemplateInfo.GetFullHtmlFieldName("") + ".Minutes").HtmlAttributes(new { style = "width: 30px;", id= ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Minutes" }).Spinners(false) :
@Html.Kendo().IntegerTextBox().Name(ViewData.TemplateInfo.GetFullHtmlFieldName("") + ".Seconds").HtmlAttributes(new { style = "width: 30px;", id= ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Seconds" }).Spinners(false)

Kind Regards,
Alex Hajigeorgieva
Progress Telerik

0
William
Top achievements
Rank 1
answered on 18 Aug 2020, 03:47 PM

Hi Alex,

 

Thanks for the update, maybe I'm not explaining very clearly, or im not understanding what the solution is, but the issue is not with the editor, is with the column binding itself

this doesnt work:

columns.Bound(p => p.ExecutionTime);

 

 

but this does -- but since the field is not bound to any column then i cant update it.

 

columns.Template(@<text></text>).ClientTemplate("#=FormatTimeFromTimeSpan(data.ExecutionTime)#").Title("Execution Time").Width(150);    //displays ok, no edit
function FormatTimeFromDateTime(timeSpanFieldVal) {
    if (timeSpanFieldVal == null)
        return "---";
 
    var d = new Date(timeSpanFieldVal.TotalMilliseconds);
    return kendo.toString(d, 'T');
}

 

This is the definition of the field:

public Nullable<System.TimeSpan> ExecutionTime { get; set; }

 

So really the issue is that I'm not able to bind a nullable timespan to a grid, which is a fault in the functionality of the Kendo MVC library.

 

Also, Im using Kendo.MVC.dll, version 2019.1.115.545; I noticed that the version in the sample seems to be much older.

Thanks,

William

 

0
Tsvetomir
Telerik team
answered on 20 Aug 2020, 10:58 AM

Hi William,

Indeed, a ClientTemplate is needed in order for the TimeSpan to be displayed as expected. This is due to the fact that the grid is actually initialized and powered by JavaScript where a TimeSpan data type is non-existent. Therefore, the adjustment has to be done additionally.

What I can recommend is that you add the ClientTemplate to the column declaration:

        columns.Bound(o => o.Time).ClientTemplate("#if (data.Time) {# #:kendo.toString(Time.Hours, '00')#:#:kendo.toString(Time.Minutes, '00')#:#:kendo.toString(Time.Seconds, '00')# #}#").EditorTemplateName("TimePickerEditor");

 

Regards,
Tsvetomir
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
Date/Time Pickers
Asked by
Azmi
Top achievements
Rank 2
Answers by
Dimiter Topalov
Telerik team
AMF
Top achievements
Rank 2
Alex Hajigeorgieva
Telerik team
Curt
Top achievements
Rank 1
William
Top achievements
Rank 1
Tsvetomir
Telerik team
Share this question
or