Razor Web Application, Keno grid InCell edition using a date picker control unable to return the updated value to server

1 Answer 24 Views
Date/Time Pickers Grid
Keith
Top achievements
Rank 1
Keith asked on 20 Oct 2021, 05:59 PM

Need an example of how to use a date picker to change the date field in a Keno grid. The examples I can find only show a dropdown. I have not problem get this to work on the client side. But I can not find anything that show how to return the updated value back to the server. 

Razor page:

 @(Html.Kendo().Grid<Pages.EditContract>()
                .Name("grid")
                .Editable(editable => editable.Mode(GridEditMode.InCell))
                .Columns(columns =>
                {
                    columns.Bound(p => p.StartDate);
                    columns.Bound(p => p.EndDate).ClientTemplate("#=EndDate#").Sortable(false).Width(180).Format("MM/dd/yyyy");                  
                })
                .DataSource(ds => ds.Ajax()
                    .Model(model =>
                    {
                        model.Id(p => p.Id);
                        model.Field(p => p.StartDate).Editable(false);
                        model.Field(p => p.EndDate).Editable(true);

                    })
                    .Read(r => r.Url("/Edit?handler=Read").Data("forgeryToken"))
                    .Update(r => r.Url("/Edit?handler=Update").Data("forgeryToken"))
                    .Model(m => m.Id(id => id.Id))
                    .PageSize(4)
                )
                //.Events(ev => ev.DataBound("db"))
            )

Edit Template:

@model ContractorManagment.Models.Contract

@(Html.Kendo().DatePicker()
        .Name("EndDate") // The name of the DatePicker is mandatory. It specifies the "id" attribute of the widget.
        .Format("MM/dd/yyyy")
        //.Value(Model.EndDate) // Sets the value of the DatePicker.        
    )

If it was not in a grid all you have to do is set the .Value property. But that does not work when it is in a grid.

 

Keith
Top achievements
Rank 1
commented on 21 Oct 2021, 03:14 PM

Was missing the

.HtmlAttributes(new { data_bind = "value: EndDate" })

But now I have an issue with the Datepicker ignoring the Format("MM/dd/yyyy")  and returning the string "Fri Jun 01 2029 00:00:00 GMT-0500 (Central Daylight Time)" which is not a valid date. Any attempt to format it or convert it to a date return, error not a recognizable date. 

Any way for getting the Datepicker recognize the Format parameter for the date it returns? 

 

1 Answer, 1 is accepted

Sort by
0
Stoyan
Telerik team
answered on 25 Oct 2021, 01:05 PM | edited on 25 Oct 2021, 01:05 PM

Hi Keith,

Thanks for sharing your code.

The solution you have implement is one viable way to configure the EditorTemplate of a Grid's column to be a DatePicker.

Alternatively, the Grid internally sets the editor of the field to DatePicker when the field is bound to an object of type DateTime returned by the PageModel.

public class EditContract
{
    ...  
    public DateTime EndDate{ get; set; }
     ...
}

 

Concerning the issue with the formatting of the date, the .Format() property is not taking effect when a ClientTemplate is used. To resolve this format the value of the field with the use of the kendo.toString method:
 columns.Bound(p => p.EndDate).ClientTemplate("#: kendo.toString(data.EndDate, 'MM/dd/yyyy' )# ");

I hope the information above is useful. Please let me know, if you have further questions.

Regards,
Stoyan
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/.

Keith
Top achievements
Rank 1
commented on 26 Oct 2021, 01:12 PM

I decided to just use the default datetimepicker the grid use if the field is of type datetime. My issue now is that I do not want the StartDate field editable in Edit mode.  This javascript handles this. But it is still editable through the datetimepicker template that the grid displays when it the field is a datetime field.  I can not seem to disable or suppress the template using javascript. Is there a way disable or keep the template from displaying during Edit mode?     

script type="text/javascript">
    function edit(e) {
        if (e.model.isNew() == false) {
            $('[name="StartDate"]').attr("readonly", true);
        }
    }
</script>

  @(Html.Kendo().Grid<Models.Contract>()
                .Name("grid")
                .Editable() 
                //.Scrollable()
                .ToolBar(x =>
                {
                    x.Create();
                })
                .Columns(columns =>
                {
                    columns.Bound(p => p.Id);
                    columns.Bound(p => p.StartDate).Format("{0:MM/dd/yyyy}"); 
                    //columns.Bound(p => p.EndDate).ClientTemplate("#=EndDate#").Sortable(false).Width(180).Format("MM/dd/yyyy");
                    columns.Bound(p => p.EndDate).Format("{0:MM/dd/yyyy}"); //.EditorTemplateName("EndDate").Width(180);
                    columns.Command(column =>
                    {
                        column.Edit();
                    });
                })
                 .DataSource(ds => ds.Ajax()
                    .Batch(false)
                    .Model(model =>
                    {
                        model.Id(id => id.Id);
                        model.Field(p => p.Id).Editable(false);
                        model.Field(p => p.StartDate).Editable(true);
                        model.Field(p => p.EndDate).Editable(true);

                    })
                    .Read(r => r.Url("/Edit?handler=Read").Data("forgeryToken"))
                    .Update(r => r.Url("/Edit?handler=Update").Data("forgeryToken"))
                    .Create(c => c.Url("/Edit?handler=Create").Data("forgeryToken"))
                    .Events(events => events.Error("grid_error")) // Handle the "error" event.
                    .PageSize(4)
                )
                .Events(events => events.Edit("edit"))
                .Pageable()
            )

 

Source:

<div id="grid" name="grid"></div><script>kendo.syncReady(function(){jQuery("#grid").kendoGrid({"edit":edit,"columns":[{"title":"Id","field":"Id","filterable":{"messages":{"selectedItemsFormat":"{0} selected items"},"checkAll":false},"encoded":true},{"title":"Start Date","field":"StartDate","format":"{0:MM/dd/yyyy}","filterable":{"messages":{"selectedItemsFormat":"{0} selected items"},"checkAll":false},"encoded":true,"editor":"\r\n\u003cinput data-val=\"true\" data-val-required=\"The StartDate field is required.\" id=\"StartDate\" name=\"StartDate\" type=\"text\" value=\"\" /\u003e\u003cscript\u003ekendo.syncReady(function(){jQuery(\"#StartDate\").kendoDateTimePicker({});});\u003c/script\u003e\u003cspan class=\"field-validation-valid\" data-valmsg-for=\"StartDate\" data-valmsg-replace=\"true\"\u003e\u003c/span\u003e"},{"title":"End Date","field":"EndDate","format":"{0:MM/dd/yyyy}","filterable":{"messages":{"selectedItemsFormat":"{0} selected items"},"checkAll":false},"encoded":true,"editor":"\r\n\u003cinput data-val=\"true\" data-val-required=\"The EndDate field is required.\" id=\"EndDate\" name=\"EndDate\" type=\"text\" value=\"\" /\u003e\u003cscript\u003ekendo.syncReady(function(){jQuery(\"#EndDate\").kendoDateTimePicker({});});\u003c/script\u003e\u003cspan class=\"field-validation-valid\" data-valmsg-for=\"EndDate\" data-valmsg-replace=\"true\"\u003e\u003c/span\u003e"},{"command":[{"text":"Edit","name":"edit"}]}],"pageable":{"buttonCount":10},"scrollable":false,"editable":{"confirmation":"Are you sure you want to delete this record?","confirmDelete":"Delete","cancelDelete":"Cancel","mode":"inline","create":true,"update":true,"destroy":true},"toolbar":[{"text":"Add new record","name":"create"}],"dataSource":{"type":(function(){if(kendo.data.transports['aspnetmvc-ajax']){return 'aspnetmvc-ajax';} else{throw new Error('The kendo.aspnetmvc.min.js script is not included.');}})(),"transport":{"read":{"url":"/Edit?handler=Read","data":forgeryToken},"prefix":"","update":{"url":"/Edit?handler=Update","data":forgeryToken},"create":{"url":"/Edit?handler=Create","data":forgeryToken}},"pageSize":4,"page":1,"groupPaging":false,"total":0,"serverPaging":true,"serverSorting":true,"serverFiltering":true,"serverGrouping":true,"serverAggregates":true,"filter":[],"error":grid_error,"schema":{"data":"Data","total":"Total","errors":"Errors","model":{"id":"Id","fields":{"Id":{"editable":false,"type":"number"},"StartDate":{"type":"date"},"EndDate":{"type":"date"},"StatusId":{"type":"number"},"ContractorId":{"type":"number"},"Status":{"type":"object"}}}}}});});</script>

 

Stoyan
Telerik team
commented on 26 Oct 2021, 02:25 PM

Hi Keith,

Try setting the Editable property of the DataSource's model to false:
                  .Model(model =>
                    {
                        model.Id(id => id.Id);
                        model.Field(p => p.Id).Editable(false);
                        model.Field(p => p.StartDate).Editable(false);
                        model.Field(p => p.EndDate).Editable(true);
                    })
Alternatively, you can configure the .Editable property of the StartDate column and return false in the JS handler function:
columns.Bound(p => p.StartDate).Editable("startDateEdit");
function startDateEdit(){
    return false;
}

Regards,
Stoyan
Keith
Top achievements
Rank 1
commented on 26 Oct 2021, 02:37 PM

It has to be editable in the Create new record. So that is why I include the JavaScript. The JavaScript works for the StartDate text input field. It makes it read only when it is in edit mode. But you can still update the start date field using the default datetime picker. When in edit mode the datetime picker needs to be hidden or disabled, how do  Id that?  
Stoyan
Telerik team
commented on 29 Oct 2021, 02:18 PM

Hello Keith,

Thanks for the clarification. To achieve this requirement utilize the model emitted as content of the starDateEdit function. Use its isNew method to determine whether the method is newly created or not.

function startDateEdit(e){
        if (e.isNew()) {
            return true;
        }
        return false;
}

When the model is not newly created return false to set up the field as non-editable. 

 
Keith
Top achievements
Rank 1
commented on 01 Nov 2021, 04:35 PM

Yes, That worked. Thanks!
Tags
Date/Time Pickers Grid
Asked by
Keith
Top achievements
Rank 1
Answers by
Stoyan
Telerik team
Share this question
or