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

Trying to update 2 Kendo DateTimePickers in my Kendo Grid but the controllers doesn't recognize my changes.

1 Answer 48 Views
Date/Time Pickers
This is a migrated thread and some comments may be shown as answers.
Guillermo
Top achievements
Rank 1
Guillermo asked on 03 Jul 2013, 12:04 AM
Hi, 

Basically I am trying to update 3 of my fields in my kendo Grid, 2 of them are kendoDateTimePickers, but when my changes are picked up by my controllers it tell me about an error that includes the DateTimePickers.

So the is the code I have so far:

======================================================================================================================================================================================

My Home-Index.js:

//New WO to schedule grid
    workOrdersSchedulingDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                // the remote service url
                url: '/sdata/api/dynamic/-/WorkOrders?where=(Status eq \'Unassigned\')&include=Customer,AssignedTo&count=200'
            }
        },
        type: 'sdata',
        serverSorting: true,
        sort: { field: "Priority", dir: "desc" },   
        schema: { data: "$resources",
            model: {
                fields: {$key: { editable: false, defaultValue: "00000000-0000-0000-0000-000000000000" },
                    Priority: { editable: false, nullable: true },
                    Customer: { editable: false, nullable: true },
                    LocationCity: { editable: false, nullable: true },
                    ServiceDate: { editable: true, nullable: true, type: "date" },
                    ServiceEndDate: { editable: true, nullable: true, type: "date" },
                    AssignedTo: { editable: true, nullable: true }
                }
            },
            parse: function (data) {
                $.each(data.$resources, function(idx, item) {
                    if (item.AssignedTo == null) {
                        item.AssignedTo = { $key: "", FirstName: "", LastName: ""} ;
                    }
                });
                return data;
            }
        },
        change: function () {
            var count = this.total();
            $("#workOrdersSchedulingCount").text(count);
            if (count == 0) {
                $("#zeroWorkOrdersToScheduling").removeClass("displayNone");
                $("#workOrdersSchedulingTable").addClass("displayNone");
                $("#workOrdersSchedulingFooter").addClass("displayNone");
            } else {
                $("#zeroWorkOrdersToScheduling").addClass("displayNone");
                $("#workOrdersSchedulingTable").removeClass("displayNone");
                $("#workOrdersSchedulingFooter").removeClass("displayNone");
                $("#unassignedBackground").removeClass("displayNone");
                $("#unassignedUnderline").removeClass("displayNone");
            }
        }
    });

    var technicianDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "/sdata/api/dynamic/-/servicesuser?where=Role eq 'Technician'&include=user",
            }
        },
        type: 'sdata',
        schema: { data: "$resources",
            parse: function (data) {
                $.each(data.$resources, function(idx, item) {
                    item['FirstLastName'] = concatFirstLastName(item.User.FirstName, item.User.LastName);
                    item['Id'] = item.User.$key;
                    item['FirstName'] = item.User.FirstName;
                    item['LastName'] = item.User.LastName;
                });
                return data;
            }
        }
    });
    
    var schedulingGrid = $("#workOrdersSchedulingTable").kendoGrid({
        dataSource: workOrdersSchedulingDataSource,
        pageable: false,
        sortable: false,
        scrollable: true,
        height: 250,
        dataBound: function () {
            var grid = this;
            $.each(grid.tbody.find('tr'), function () {
                var model = grid.dataItem(this);
                //if Role equals NoRoleAssigned, attach star icon ahead of user name
                if (model.Priority === "Low") {
                    $('[data-uid=' + model.uid + ']' + '>td:first-child').prepend('<span class="staricon">&nbsp;<img src="/Content/images/lowPriority.png" />&nbsp;&nbsp;&nbsp;</span>');
                }
                else if (model.Priority === "Regular") {
                    $('[data-uid=' + model.uid + ']' + '>td:first-child').prepend('<span class="staricon">&nbsp;<img src="/Content/images/regularPriority.png" />&nbsp;&nbsp;&nbsp;</span>');
                }
                else {
                    $('[data-uid=' + model.uid + ']' + '>td:first-child').prepend('<span class="staricon">&nbsp;<img src="/Content/images/criticalPriority.png" />&nbsp;&nbsp;&nbsp;</span>');
                }
            });

            $("table tr").hover(
                function () {
                    $(this).toggleClass("k-state-hover");
                }
            );
        },
        columns: [
            { hidden: true, field: "$key", title: "Key", template: kendo.template($("#tempId").html()) },
            { field: "Priority", title: "Priority", width: "75px"},
            { field: "Customer", title: "Customer", width: "119px", template: "<div style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;' title='#= Customer.Name #'>#= Customer.Name # </div>"},
            { field: "LocationCity", title: "Location", width: "95px", template: "<div style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;' title='#= LocationCity #'>#= LocationCity?LocationCity:'N/A' # </div>" },
            { field: "ServiceDate", title: "Start", width: "155px", format: "{0:MM/dd/yyyy hh:mm tt}", template: kendo.template($("#tempStartDate").html()), editor: startDateTimeEditor },
            { field: "ServiceEndDate", title: "End", width: "155px", format: "{0:MM/dd/yyyy hh:mm tt}", template: kendo.template($("#tempEndDate").html()), editor: endDateTimeEditor },
            { field: "AssignedTo", title: "Technician", width: "145px", template: kendo.template($("#tempAssignedTo").html()), editor: assignedToDropDownEditor }
        ], editable: {
            template: null,
            createAt: "bottom"
        }
    });
    
//My editors
    function assignedToDropDownEditor(container, options) {
        $('<input id="technicianDropDown" data-text-field="FirstLastName" data-value-field="Id" data-bind="value:' + options.field + '"/>')
            .appendTo(container)
            .kendoDropDownList({
                autoBind: false,
                dataSource: technicianDataSource,
                index: -1
            });
}

    function startDateTimeEditor(container, options) {
        $('<input id="serviceDateEditor" data-text-field="ServiceDate" data-value-field="ServiceDate" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDateTimePicker({
                    autoBind: false,
                    format: "{0:MM/dd/yyyy hh:mm tt}",
                });
    }
    
    function endDateTimeEditor(container, options) {
        $('<input id="serviceEndDateEditor" data-text-field="ServiceEndDate" data-value-field="ServiceEndDate" data-bind="value:' + options.field + '"/>')
                .appendTo(container)
                .kendoDateTimePicker({
                    autoBind: false,
                    format: "{0:MM/dd/yyyy hh:mm tt}",
                });
    }

======================================================================================================================================================================================

My templates that are on my Index.cshtml
<script id="tempStartDate" type="text/x-kendo-tmpl">
        <div id="serviceDate">#= kendo.toString(new Date(ServiceDate),"MM/dd/yyyy hh:mm tt")  # </div>
        <input type='hidden' name='WorkOrders[#= workOrdersSchedulingDataSource.data().indexOf(data) #].ServiceDate' value='#= ServiceDate #' />
</script> 

<script id="tempEndDate" type="text/x-kendo-tmpl">
        <div id="serviceEndDate">#= kendo.toString(new Date(ServiceEndDate),"MM/dd/yyyy hh:mm tt") #</div>
        <input type='hidden' name='WorkOrders[#= workOrdersSchedulingDataSource.data().indexOf(data) #].ServiceEndDate' value='#= ServiceEndDate #' />
</script> 
    
<script id="tempAssignedTo" type="text/x-kendo-tmpl">
        <div>#=concatFirstLastName(AssignedTo.FirstName, AssignedTo.LastName)#</div>
        <input type='hidden' name='WorkOrders[#= workOrdersSchedulingDataSource.data().indexOf(data) #].AssignedTo.Id' value='#= AssignedTo.Id #' />
</script> 

<script id="tempId" type="text/x-kendo-tmpl">
        <input type='hidden' name='WorkOrders[#= workOrdersSchedulingDataSource.data().indexOf(data) #].Id' value='#= $key #' />
</script>

======================================================================================================================================================================================

And finally my HomeController:

amespace Nephos.Services.Site.Controllers
{
    [UMAuthorize]
    public class HomeController : PublicController
    {
        // GET: /Home/
        private const string ScheduleSaved = "Changes saved.";
        private readonly ISession _session;

        public HomeController()
        {
            _session = ContainerManager.ResolveTenantSession();
        }

        public ActionResult Index()
        {
            var viewModel = new ScheduleViewModel();
            return View(viewModel);
        }

        // POST: /Home/SaveInvoice
        /// <summary>
        /// </summary>
        /// <param name="scheduleViewModel"></param>
        /// <returns>The Json Result</returns>
        [HttpPost]
        public JsonResult Save(ScheduleViewModel scheduleViewModel)
        {
            var msg = ScheduleSaved;
            var type = NotificationType.Success;
            
            foreach (var workOrder in scheduleViewModel.WorkOrders)
            {
                if ((workOrder.AssignedTo.Id == Guid.Empty)) continue;
                var targetWorkOrder = _session.Get<WorkOrder>(workOrder.Id);

                if (targetWorkOrder == null)
                {
                    LogAndThrowEntityNotFound("work order", workOrder.Id);
                }
                else
                {
                    var targetUser = _session.Get<User>(workOrder.AssignedTo.Id);
                    if (targetUser == null)
                    {
                        LogAndThrowEntityNotFound("user", workOrder.AssignedTo.Id);
                    }
                    else
                    {
                        targetWorkOrder.AssignedTo = targetUser;
                        targetWorkOrder.Status = WorkOrderStatus.Assigned;
                        targetWorkOrder.ServiceDate = workOrder.ServiceDate;
                        targetWorkOrder.ServiceEndDate = workOrder.ServiceEndDate;

                        _session.Transaction.Begin();
                        _session.SaveOrUpdate(targetWorkOrder);
                        _session.Transaction.Commit();
                    }
                }
            }

            return Json(new Notification { Message = msg, Type = type }, "application/json",
                           JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Log And Throw NotFound exception
        /// </summary>
        /// <param name="entityName">The entityName that could not be found in the database.</param>
        /// <param name="entityId">The entityId that could not be found in the database.</param>
        private void LogAndThrowEntityNotFound(String entityName, Guid entityId)
        {
            LoggingHelper.Error(string.Format("Could not find {0} {1}.", entityName, entityId), TenantID, ProductUserId);
            throw SDataErrors.EntityNotFound();
        }
    }
}

So basically my error is here:
targetWorkOrder.ServiceDate = workOrder.ServiceDate;
targetWorkOrder.ServiceEndDate = workOrder.ServiceEndDate;

_session.Transaction.Begin();
_session.SaveOrUpdate(targetWorkOrder);
_session.Transaction.Commit();

I am pretty sure it is related with my template, or my editor, I have tried so many things and still is like I don't get the proper date from the dateTimePicker, so it says the date is SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. And since the is not null to the date it goes to the minimum value which means it is like it is null, it is not picking anything. So I have no idea what I am doing wrong, please help me =).

I attached a file to show the error that displays on the controller.
Another screen to show what FireBug shows.

Thank you,

Guillermo Sanchez



1 Answer, 1 is accepted

Sort by
0
Daniel
Telerik team
answered on 04 Jul 2013, 03:23 PM
Hello,

Are you posting the data via a form? If yes, then you should format the values in the hidden inputs e.g.

<input type='hidden' name='WorkOrders[#= workOrdersSchedulingDataSource.data().indexOf(data) #].ServiceDate' value='#= kendo.toString(ServiceDate,"G") #' />
Regards,
Daniel
Telerik
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
Tags
Date/Time Pickers
Asked by
Guillermo
Top achievements
Rank 1
Answers by
Daniel
Telerik team
Share this question
or