@{
	ViewData["Title"] = "Home Page";
}

<div class="row">
	<div class="col-xs-18 col-md-12">
		@(Html.Kendo().Grid<Sample.Models.OrderViewModel>()
				.Name("grid")
				.Columns(columns =>
				{
					columns.Bound(p => p.OrderID).Filterable(false);
					columns.Bound(p => p.Freight);
					columns.Bound(p => p.OrderDate).Format("{0:MM/dd/yyyy}");
					columns.Bound(p => p.ShipName);
					columns.Bound(p => p.ShipCity);
                    columns.Bound(p => p.Organization).ClientTemplate("#= data.Organization ? data.Organization.text : '' #");
				})
                .ToolBar(tb=>tb.Save())
                .Editable(ed=>ed.Mode(GridEditMode.InCell))
				.Pageable()
				.Sortable()
				.Scrollable()
				.Filterable()
                .Events(ev=>ev.CellClose("onCellClose"))
				.HtmlAttributes(new { style = "height:550px;" })
				.DataSource(dataSource => dataSource
					.Ajax()
					.PageSize(20)
                    .Batch(true)
                    .Model(m=>m.Id(id=>id.OrderID))
					.Read(read => read.Action("Orders_Read", "Grid"))
					.Update(update => update.Action("Orders_Update", "Grid"))
				)
		)
	</div>
</div>
<script>
    function onCellClose(e) {
        var headerIndex = $("#grid th[data-field='Organization']").index(); // get the index of the header cell
         
        if (e.container.index() == headerIndex) { // execute the logic if the edited cell is in the Organization column
            var treeView = e.container.find("[data-role='dropdowntree']").getKendoDropDownTree().treeview; // get a reference to the internal TreeView widget
            var selectedRow = treeView.select(); // get the selected item
            var dataItem = treeView.dataItem(selectedRow); // get the selected data item
            var customObject = { id: dataItem.value, text: dataItem.text, hasChildren: dataItem.hasChildren }; // compose the custom object

            var gridRow = e.container.closest("tr"); // get a reference to the current row
            var gridDataItem = $("#grid").getKendoGrid().dataItem(gridRow); // get a reference to the data item of the row
            gridDataItem.set("Organization", customObject) // set the field to be the custom object
        }
    }
</script>