Telerik mvc grid datepicker not showing up the grid date in the Inline Edit mode
Hi, it
seems the most common problem in telerik grid inline edit mode that the
datepicker is empty or the date format changes while you edit a row. I have
tried with various tricks by changing the format in Views\Shared\EditorTemplates\DateTime.cstml, sometimes it works but
sometimes we need some customer format to show the user while picking up the
date. For example we are showing the date in this format
19/July/2012
but we want to show the
user in this format while he pick a new date to change
19/07/2012
So let me explain how we
can customize date time format in Telerik mvc grid inline edit mode.
I guess you have no need to touch Views\Shared\EditorTemplates\DateTime.cstml for this purpose.
1. Add a client event in your grid
.ClientEvents(events
=> events
.OnRowDataBound("onRowDataBound")
.OnEdit("onEdit")
.OnSave("onSave")
.OnLoad("onLoad")
.OnDelete("onDelete")
.OnDataBound("OnDataBound")
.OnDataBinding("OnDataBinding")
.OnComplete("onComplete")
)
2. Add the onEdit
function to your javascript area of the code
function onEdit(e) {
//lets get the current date of the row
var dataItem = e.dataItem;
var sDate = new Date(dumpDate(dataItem));
if (isNaN(sDate.getMonth())) {
sDate = new Date();
}
//this will apply the
format to the date picker that you want to show in the editing mode
$('#GridDate').val($.telerik.formatString('{0:MM/d/yyyy}', sDate));
$('#GridDate').focus();
}
3. The
dumpDate function will return you the date which was currently in the row you
are going to edit. So add a function dumpDate to get the date.
function
dumpDate(obj) {
var
result = [];
$.each(obj, function
(key, value) { if (key.toString() == "GridDate") { result.push(value); } });
return
result;
}
Note: you can change the name of function dumpDate to any other.
4. You can
use any custom format to show the date in the grid
columns.Bound(o =>
o.GridDate).Width(220).Title("Date").Format("{0:dd/MMM/yy}");
Hope this help someone. Thanks
How can I set the value in DateTime picker to DateTime.Now while adding new record ??
ReplyDeleteThat would be simple. Use the below code and populate your field.
Deletevar now = new Date();
now.format("dd/M/yy h:mm tt");
Its been a years i have played with MVC so i am not sure now with exact syntax. But it could be somthing i have placed above.
Good Luck