Kendo UI Grid: Method "removeRow" deletes all events of the grid - kendo-ui

I have a Kendo UI Grid and added mouse events to the grid by jQuery (e.g. click). This is working without any problem. But by deleting a row in the grid, all events of the grid are also deleted. What am I doing wrong?
This is my code to delete a row:
var rowToDelete = $(this).closest("tr");
var grid = $("#gridId").data("kendoGrid");
grid.removeRow(rowToDelete);
I added a button to each row of the grid, added a click event to these buttons which deletes the corresponding row. After the row is deleted, the click events of all other buttons are removed. The same with the mouse-over events of a grid column.
Thanks for your help!

Please try with the below code snippet.
VIEW
<script>
function gridDataBound(e) {
var grid = $("#Grid").data("kendoGrid");
grid.tbody.find(">tr").click(function () {
$("#divTest").html('Row Index Clicked :' + $(this).index());
});
}
function DeleteRow(obj) {
var rowToDelete = $(obj).parent().parent()
var grid = $("#Grid").data("kendoGrid");
grid.removeRow(rowToDelete);
}
</script>
#(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.ID);
columns.Bound(p => p.Name);
columns.Template(#<text></text>).ClientTemplate("<input type='button' class='k-button' value='Delete' onclick='DeleteRow(this);' />");
})
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Grid_Read", "Home"))
)
.Events(e => e.DataBound("gridDataBound"))
)
<div id="divTest"></div>
CONTROLLER
public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
{
List<TestModels> models = new List<TestModels>();
for (int i = 0; i < 5; i++)
{
TestModels t1 = new TestModels();
t1.ID = i;
t1.Name = "Name" + i;
models.Add(t1);
}
return Json(models.ToDataSourceResult(request));
}
MODEL
public class TestModels
{
[Display(Name = "ID")]
public int ID { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
}
Let me know if any concern.

You are not posting all the code so I have to guess...
What is happening is that you set an event handler associated to the elements just after the initialization and therefore for some particular HTML elements but there are circumstances under which Kendo UI grid gets regenerated (basically the system removes the table and generates a new one).
If you want to set an event handler not for the current table content but for any future one, you might use jQuery on event but using three arguments where the second is the selector (in previous version of jQuery this was achieved with live function but now is deprecated, so if your jQuery version supports it better use on).
What you have to do is:
$("#grid").on("click", ".my-selector", function(e) {
var rowToDelete = $(this).closest("tr");
var grid = $("#gridId").data("kendoGrid");
grid.removeRow(rowToDelete);
});
Where my-selector is a CSS class attribute that you probably already set for identifying the remove button.

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.

Telerik/ Kendo MVC Grid, Load grid on demand, not on page load

i found a couple examples on how to do this, and none of them are working for me.
Here is my Telerik MVC grid:
#(Html.Kendo().Grid<PlayerStatsViewModel>()
.Name("PlayerStats")
.Columns(columns =>
{
columns.Bound(o => o.PlayerId);
columns.Bound(o => o.FirstName);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(p => p.PlayerId))
.Read(read => read.Action("PlayerStats_Read_Bound", "Contest").Data("getPlayerId"))
).AutoBind(false)
)
Open modal with my grid
I set autobind(false) which prevents page load. After a user clicks a link i open a modal with my grid, and need to pass in a parameter.
// open modal
$(document).on("click", "#openStatsModal", function () {
playerId = $(this).data('id'); // get parameter from click
loadPlayerStats();
});
function getPlayerId() {
return {
playerId: playerId
}
}
Make ajax call?
My click method works and i get my player id. Then i try and make my grid call.
function loadPlayerStats() {
var grid = $("#PlayerStats").data("playerStats");
alert(grid); // returns undefined
//grid.ajaxRequest(); this didnt work either
grid.dataSource.read(); // Cannot read property 'dataSource' of undefined
}
Action method
Never gets called unless i turn off autobind
public ActionResult PlayerStats_Read_Bound([DataSourceRequest]DataSourceRequest request, int playerId)
{
// some code
return Json(result)
}
Just try:
var grid = $("#PlayerStats").data("kendoGrid");
and then:
grid.dataSource.read();

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

Kendo Editor Templates (Grid)

I'm trying to populate a dropdownlist for use in my Kendo Grid using Editor Templates.
My StatesEditor.cshtml contains:
#(Html.Kendo().DropDownList()
.Name("State")
.DataValueField("StateID")
.DataTextField("ShortName")
.BindTo((System.Collections.IEnumerable)ViewData["states"]))
In my Controller I have:
public ActionResult Index()
{
var db = new ACoreEntities();
db.Configuration.ProxyCreationEnabled = false;
var states = db.StateLookups;
var stateList = states.Select(state => state.ShortName);
ViewData["states"] = stateList;
return View("~/Views/System/PMarkup/Index.cshtml");
}
In my actual grid, when I click the 'Edit' button for the row I get a dropdownlist that contains 51 'undefined' entries.
I ended up creating a State model then in my ActionResult I changed my code to:
ViewData["states"] = new ACoreEntities()
.StateLookups
.Select(s => new State
{
Id = s.StateID,
ShortName = s.ShortName
})
.OrderBy(s => s.ShortName);

Kendo ui Grid Hierarchy error on grid.AddRow() when there is an enum column in grid

I have a Kendo Grid Hierarchy and an entity which has one enum property and some other properties with other .net primitive types and also there is a toolbar button named AddNewRecord on grid. When the user presses the AddNewRecord button, it must add a new row to grid and shows a partial view in the grid (because it is Hierarchy Grid). When I comment the enum property in entity, everything works perfect; otherwise, the AddNewRecord button does nothing at all.
Does anybody know what the problem is?
Thanks in advance
.ToolBar(toolbar => toolbar.Custom().Text("AddNewRecord").Url("#").HtmlAttributes(new {#class="testClass"}))
.ClientDetailTemplateId("EntityTemplate")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id("Id"))
.Read(read => read.Action("BaseInfoGeneralForm", "BaseInfo"))
$(".testClass").click(function () {
var grid = $("#Grid").data("kendoGrid");
grid.addRow();
$(".k-grid-edit-row").appendTo("#grid tbody");//Add New Row
grid.expandRow(grid.tbody.find("tr.k-master-row").first());//Expand newly added row
public class FileStatus : EntityBase
{
public FileStatus()
{
}
public virtual string Title { get; set; }
public virtual Status Ended { get; set; }
}
}
this.expandRow(this.tbody.find("tr.k-master-row")[0]);
this.expandRow(this.tbody.find("tr.k-master-row")[1]);
this.expandRow(this.tbody.find("tr.k-master-row")[2]);
this.expandRow(this.tbody.find("tr.k-master-row")[3]);
this.expandRow(this.tbody.find("tr.k-master-row")[4]);
},

Resources