Kendo MVC - Need DatePicker in a Grid - kendo-ui

I have the following grid with a date picker:
#(Html.Kendo().Grid<ScheduleViewModel>()
.Name("ScheduleGrid")
.AutoBind(true)
-
)
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Columns(columns =>
{
columns.Bound(s => s.Name).Title("Schedule").Filterable(true).Width(150).HtmlAttributes(new { style = "text-align: left" });
columns.Bound(s => s.StartTime).Width(100).Title("Start Time").ClientTemplate((
#Html.Kendo().DatePicker()
.Name("StartTimePicker")
.Value("#=StartTime#")
//.Format("{0:dd/MM/yyyy}")
.ToClientTemplate()).ToHtmlString());
columns.Bound(s => s.Enabled).Width(100).ClientTemplate("<input type='checkbox' #=Enabled ? checked='checked' : '' # class='sda-checkbox' />").HtmlAttributes(new { #class = "text-center" });
columns.Command(command => command.Custom("Save").Click("saveSchedules")).Width(80).HtmlAttributes(new { #class = "text-center" });
})
However, the date picker doesn't display correctly. Instead it is just a text box. What am I doing wrong?
EDIT (and I also switched to use a Time Picker instead of a Date Picker):
I did as #FrozenButcher suggested, but this still doesn't work. This is what happens now:
Bring up page and you get this, which does not LOOK like a Time Picker, but is. No clock icon, and you can't see the value:
Click in the box and you get this:
Obviously you can now see the time, but no clock icon.
Finally, click in the Time Picker on the second line and you get this:
Any help in resolving this is greatly appreciated.

You have to ensure unique ids for your inputs, wrapper for datepicker is defined through the name property.
change it to a dynamic name .Name("StartTimePicker"+ lineNumber)

Related

Kendo TimePicker in a Grid: How Do I Get the Value?

I have the following time picker in a Kendo grid:
columns.Bound(s => s.StartTime).Title("Start Time").Width(76).ClientTemplate((
#Html.Kendo().TimePicker()
.Name("StartTimePicker" + "#=ID#")
.Format("HH:mm:ss")
.Interval(15)
.HtmlAttributes(new { data_bind = "value: StartTime" })
.ToClientTemplate()).ToHtmlString());
This works as intended. I also have the following button in the grid:
columns.Command(command => command.Custom("Save").Text("<span class=\"k-icon k-i-check\"></span>Save").Click("saveSchedule")).Width(80).HtmlAttributes(new { #class = "text-center" });
I want to access the value of the time picker in my saveSchedule function, which is:
function saveSchedule(e) {
e.preventDefault();
// etc
// need code to get time here
How do I get the time that was selected in the grid?
I added this to my saveSchedule function:
var timepicker = $(e.currentTarget).closest('tr').find('.k-input');
schedule.StartTime = timepicker[0].value;
Solved the issue.

Model Empty in Popup Editor template for Kendo MVC Grid Create, No default value

I have a Kendo MVC hierarchy grid. My example is simplified for readability.
#(Html.Kendo().Grid<LeagueViewModel>(Model.Leagues)
.Name("grid_#=LeagueTypeId#")
.Columns(columns => { })
.ToolBar(toolbar =>
{
toolbar.Create().Text("Add New League(Window)");
})
.Editable(editable => editable.Mode(GridEditMode.PopUp)
.TemplateName("LeagueEdit")
.Window(w =>
{
w.Position(p => p.Top(200)); // position not working, need to center more vertically
w.Width(800);
}
)
)
.Events(e => e.Edit("leagueEdit"))
.DataSource(dataSource => dataSource
.Server()
.Model(model =>
{
model.Id(p => p.LeagueID);
model.Field(l => l.strSportId).DefaultValue("#=SportId#"); // set default value with parent grid data
model.Field(l => l.strLeagueTypeId).DefaultValue("#=LeagueTypeId#"); // set default value with parent grid data
}
)
.Read(read => read.Action("Bound_League_Read", "Configuration", new { _leagueTypeId = "#=LeagueTypeId#" }))
.Create(create => create.Action("League_Create", "Configuration"))
)
)
Here is my javascript event handler. When observing the e.model object from the handler after the create button is clicked i have the default values i set earlier with in the grid with DefaultValue("#=ParentProperty#").
function leagueEdit(e) {
// setting these with default value on model,
// had to have string variants to pass over because template expression syntax
e.model.SportId = parseInt(e.model.strSportId);
e.model.LeagueTypeId = parseInt(e.model.strLeagueTypeId);
}
LeagueEdit.cshtml
When my popup template opens, the model has no data. How do i get data into the model? I have elements in the popup editor that need the values from the parent grids.
<p>sport: #Model.SportId</p> <!-- value does not carry over -->
<p>leaguetype: #Model.LeagueTypeId</p> <!-- value does not carry over -->
In your Edit event try to find the control in popup using its Id and set the value. For example in the below code am finding a datepicker inside my popup and setting its value to the model property.
function LeagueEditEdit(e) {
var val1 = e.container.find("input[name=CallDate]").data("kendoDatePicker");
val1.value($('#CallDate').attr('value'));
e.model.CallDate = val1._value;
}

Disabling edit on Telerick MVC Grid

I have a MVC Kendo UI Grid as follows
#(Html.Kendo().Grid<SomeViewModel>()
.Name("someGrid")
.ToolBar(toolbar =>
{
toolbar.Create().Text("Add Entry");
toolbar.Save();
})
.Columns(columns =>
{
columns.Bound(p => p.Name).ClientTemplate(#"<input type='radio' name='SomeradioName'> #= Name # </input>");
columns.Bound(p => p.DateCreated).Format("{0:dddd dd MMMM yyyy}");
})
.Editable(editable => editable.Mode(GridEditMode.InCell))
.Events(e => e.DataBound("onDataBound"))
.Events(e => e.Edit("onDataEdit"))
.Selectable(selectable => selectable.Enabled(true).Mode(GridSelectionMode.Single).Type(GridSelectionType.Row))
.Scrollable()
.Filterable()
.HtmlAttributes(new {style = "height:200px;"})
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
.Batch(false)
.Events(events => events.Error("onError"))
.Model(model =>
{
model.Id(s => s.Id);
model.Field(s => s.Name).Editable(true);
model.Field(s => s.DateCreated).Editable(false);
})
.Read(read => read.Action(...))
.Create(create => create.Action(...))
.Update(create => create.Action(...))))
I want to disable In cell editing for already added entries.
So, couple of things I tried
Approach# 1:
<script>
function onDataEdit(e) {
if (!e.model.isNew()) {
var grid = this;
grid.closeCell();
}
}
</script>
Apparently this breaks the radio button selection event (.change event) which is wired up in OnDataBound.closeCell screws it up and change event no longer gets fired up
Approach# 2:
In OnDataEdit event do
$("#Name").attr("readonly", true);
This is also fine but again Change event is no longer fired on radio button click until the Cancel changes command is clicked.
Approach# 3
There seems to be another way of doing it by disabling enable as given in this link here: http://docs.telerik.com/kendo-ui/api/javascript/ui/grid#events-edit
if (!e.model.isNew()) {
// Disable the editor of the "id" column when editing data items
var numeric = e.container.find("input[name=id]").data("kendoNumericTextBox");
numeric.enable(false);
}
How do I do something similar in my case ? Couldn't get data resolved.
Any other ways ?
Update
Approach# 4
e.container.find("input[name=Name]").each(function () { $(this).attr("disabled", "disabled") });
var grid = this;
grid.cancelChanges();
This does not break the change event. However, the experience is not that great. If adding new record, if the user presses any other row the changes are canceled. They have to add new record and either hit Save or click anywhere except grid rows
You can make the columns readonly on edit, using Approach 3
function edit(e) {
if (e.model.isNew() == false) {
$('[name="Name"]').attr("readonly", true);
}
}
Also, your template doesnt have an id=Name, hence I doubt below will work for you. Instead find by name attribute as above
$("#Name").attr("readonly", true);
Refer this link for more information
I have chosen approach 4 which I updated. IF anyone has any better ideas feel free to share.

Initialize Combobox for each row of Telerik MVC Grid

I am using two Telerik MVC grids and adding selected value of one Grid to other in following way
var dataItem = this.dataItem($(e.currentTarget).closest("tr")); // This is selected row of Grid One
// Now i am going to add this to second Grid
var grid = $("#SecondGrid").data("kendoGrid");
grid.dataSource.add(dataItem);
I want to display combobox for each row of second grid. I have successfully added that and executing JS function on DataBound, but this adds combo box to only first row
// Hows second Grid looking
#(Html.Kendo().Grid<MyModel>()
.Name("SecondGrid")
.Columns(columns =>
{
columns.Bound(p => p.Id).Hidden(true);
columns.Bound(p => p.ForeName).Title("First Name");
columns.Bound(p => p.SurName).Title("Last Name");
columns.Bound(p => p.Dept);
columns.Bound(p => p.Dob).Format("{0:dd/mm/yyyy}");
columns.Bound(p => p.Relationshiptype).Title("Relationship").Template(#<text></text>).HtmlAttributes(new { #class = "templateCell" }).ClientTemplate(
Html.Kendo().ComboBox()
.Name("Relationshiptype")
.Placeholder("Select relationship...")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Husband", Value = "1"
},
new SelectListItem() {
Text = "Wife", Value = "2"
},
new SelectListItem() {
Text = "Other relative", Value = "3"
},
new SelectListItem() {
Text = "Other non relative ", Value = "4"
}
}).ToClientTemplate().ToString());
columns.Command(command => command.Custom("Deselect").Click("removePupil")).Width(180);
})
.Events(ev => ev.DataBound("initCombo"))
)
// Here is my InitCombo function
function initCombo(e) {
$(".templateCell").each(function () {
eval($(this).children("script").last().html());
});
}
Please help me sort this issue. Secondly how would i be able to traverse and get selected value of combo along with other row values .
Thanks
I suggest you creating template only by using the Template method. Like in Kendo documentation—How to Customize the Way Properties Are Displayed in Grid-Bound Column.
Next, note that you should use a unique ID for each widget created on the page. Thus, the Name value should be unique for each row. By assigning it to a string, the DOM elements rendered will have the same ID.
More detailed response with example provided is available in a forum thread, where the same questions is asked—Initialize Combobox for each row of Telerik MVC Grid

How to set up Kendo UI mvc grid with checkbox control

I am using Kendo UI MVC grid. One of the properties of the model is bool, so I need to present it in grid as checkbox. By default Kendo UI present it as "true" and "false" values in the column. So you need to first time to click to get checkbox, then second time to click to change value of the combobox. Instead of having default values from grid, I set ClientTemplate, so I got checkbox instead of "true" and "false" values.
c.Bound(p => p.GiveUp)
.Title("Giveup")
.ClientTemplate("<input type='checkbox' id='GiveUp' name='GiveUp' #if(GiveUp){#checked#}# value='#=GiveUp#' />")
.Width(50);
This grid uses batch editing and in-grid editing (GridEditMode.InCell)
.Editable(x => x.Mode(GridEditMode.InCell))
.DataSource(ds => ds.Ajax()
.ServerOperation(false)
.Events(events => events.Error("error"))
.Batch(true)
.Model(model => model.Id(p => p.Id))
.Read(read => read.Action("Orders", "Order").Data("formattedParameters"))))
So what I would like to have is ability for user to click on checkbox and change value of my model, but unfortunately that doesn't work. I can see visually checkbox's value is changed but I don't see red triangle that marks cell as changed, and when I click on add new item button, value from checkbox disappear.
Please advice on what I am doing wrong.
Thanks in advance.
For those who would like to see how full code looks like.
Home.cshtml
#(Html.Kendo().Grid<OrdersViewModel>()
.Name("Orders")
.Columns(c =>
{
c.Bound(p => p.Error)
.Title("Error")
.ClientTemplate("<input type='checkbox' #= Error ? checked='checked': '' # class='chkbx' />")
.HtmlAttributes(new {style = "text-align: center"})
.Width(50);
<script>
$(function() {
$('#Orders').on('click', '.chkbx', function() {
var checked = $(this).is(':checked');
var grid = $('#Orders').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('Error', checked);
});
});
</script>
Basically when you add/remove records from the Grid the red triangles always disappear (or when you sort/page/filter etc), the checkbox is not the problem with the red triangles.
Now for the checkbox if you create a ClientTemplate which is again a checkbox you will need to click one time to put the cell into edit mode (you will see no difference because the editor template is again a checkbox) so you will need to click second time to actually change the value.
What I suggest you as best practice is to use the approach covered here - it is way more faster (less operations for the Grid) and it easier than applying extra logic to handle the two clicks with the approach above.

Resources