I have a Kendo Grid which I would like to only be able to expand one row at a time for detail editing. What is the simplest way to do this?
#(Html.Kendo().Grid<MyModel>()
.Name("MyGrid")
.ClientDetailTemplateId("MyTemplate")
.Columns(columns =>
{
columns.Bound(b => b.Code);
columns.Bound(b => b.Name);
columns.Bound(b => b.Description);
...
columns.Command(cmd => { cmd.Edit(); cmd.Destroy(); });
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(a => a.Id))
.Create(create => create.Action("Create", "SysMaint", new { id = Model.ProjectId }))
.Read(read => read.Action("Read", "SysMaint", new { projectId = Model.ProjectId }))
.Update(update => update.Action("Update", "SysMaint"))
.Destroy(destroy => destroy.Action("Destroy", "SysMaint"))
)
)
<script id="MyTemplate" type="text/kendo-tmpl">
#(Html.Kendo().TabStrip()
.Name("TabStrip_#=Id#")
.SelectedIndex(0)
.Items(items =>
{
items.Add().Text("A").LoadContentFrom("MyPartialA", "SysMaint", new { id = "#=Id#" });
items.Add().Text("B").LoadContentFrom("MyPartialB", "SysMaint", new { id = "#=Id#" });
})
.ToClientTemplate()
)
</script>
Ends up this is really simple. Just add these few lines.
...
.Update(update => update.Action("Update", "SysMaint"))
.Destroy(destroy => destroy.Action("Destroy", "SysMaint"))
)
.Events(events => events.DetailExpand("detailExpand"))
)
<script type="text/javascript">
var expandedRow;
function detailExpand(e) {
// Only one open at a time
if (expandedRow != null && expandedRow[0] != e.masterRow[0]) {
var grid = $('#MyGrid').data('kendoGrid');
grid.collapseRow(expandedRow);
}
expandedRow = e.masterRow;
}
</script>
I hope this helps somebody.
That works except it does not remove the old detail row. Add the bit marked NEW to remove each previously opened detail row.
if (expandedRow != null && expandedRow != e.masterRow[0]) {
var grid = $('#RequestsGrid').data('kendoGrid');
grid.collapseRow(expandedRow);
expandedRow[0].nextElementSibling.remove(); //NEW
}
expandedRow = e.masterRow;
Building on Trey's answer, this version will work generically for any grid (using #vikasde's suggestion), and will also work when you have nested grids, so that the child grid when invoking the detailExpand, won't collapse its parent grid row as a side effect.
<script type="text/javascript">
function detailExpand(ev) {
var expandedRow = $(ev.sender.wrapper).data('expandedRow');
// Only one open at a time
if (expandedRow && expandedRow[0] != ev.masterRow[0]) {
var grid = $(ev.sender.wrapper).data('kendoGrid');
grid.collapseRow(expandedRow);
}
$(ev.sender.wrapper).data('expandedRow', ev.masterRow);
}
</script>
Further to the answers already here, I found that by combining hatchet's and Danny Blue's answers and using the DetailCollapse event works nicely, and will remove the underlying detail content if a row is collapsed manually.
MVC Grid configuration:
.Events(ev =>
{
ev.DetailExpand("detailExpand");
ev.DetailCollapse("detailCollapse");
})
Page scripts:
function detailExpand(ev) { // Credit hatchet
var expandedRow = $(ev.sender.wrapper).data('expandedRow');
// Only one open at a time
if (expandedRow && expandedRow[0] !== ev.masterRow[0]) {
var $grid = $(ev.sender.wrapper).data('kendoGrid');
$grid.collapseRow(expandedRow);
}
$(ev.sender.wrapper).data('expandedRow', ev.masterRow);
}
function detailCollapse(ev) {
var expandedRow = $(ev.sender.wrapper).data('expandedRow');
expandedRow.next().remove(); // Credit Danny Blue
}
Related
To my view I send Model where one property is DataTable(called Data), which I bind to Kendo Grid:
#(Html.Kendo().Grid(Model.Data)
.Name("MyGrid")
.Columns(c =>
{
if (Model.Data != null)
{
int index = 0;
foreach (System.Data.DataColumn column in Model.Data.Columns)
{
var col = c.Bound(column.ColumnName).Width("300px").EditorTemplateName("String");
if (index < 2)
{
col.Locked(true).Lockable(false);
}
index++;
}
}
})
.DataSource(dataSource => dataSource
.Ajax()
.Batch(true)
.ServerOperation(false)
.Model(model =>
{
model.Id(p => p.Row[0]);
if (Model.Data != null)
{
model.Id(Model.Data.Columns[0].ColumnName);
int index = 0;
foreach (System.Data.DataColumn column in Model.Data.Columns)
{
var field = model.Field(column.ColumnName, column.DataType);
if (index < 2)
{
field.Editable(false);
}
index++;
}
}
})
.PageSize(20)
.Create(update => update.Action("Create", "Home"))
.Update(up => up.Action("UpdateRow", "Home"))
)
.Editable(editable => editable
.Mode(GridEditMode.InCell)
)
.Selectable(selectable =>
{
selectable.Mode(GridSelectionMode.Single);
selectable.Type(GridSelectionType.Row);
})
.Scrollable(scr => scr.Height(500))
.Reorderable(reorder => reorder.Columns(true))
.Resizable(r => r.Columns(true))
.Filterable(ftb => ftb.Mode(GridFilterMode.Row))
.HtmlAttributes(new { style = "height:100%" })
.Pageable()
.Navigatable()
.Sortable()
.Groupable(g => g.ShowFooter(true))
)
The problem is with line field.Editable(false) - when I try to set true it works. It says that I do not have ID value in my DataRowView - I am pretty sure my DataTable have column called ID, I checked it like 100+times.
Exact Error:
Property with specified name: ID cannot be found on type:
System.Data.DataRowView Parameter name: propertyName
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Property with specified
name: ID cannot be found on type: System.Data.DataRowView Parameter
name: propertyName
I have baypass the problem.
I have used
.Events(events =>
{
events.Edit("edit_handler");
})
where my function looks:
<script type="text/javascript" language="javascript">
function edit_handler(e) {
var grid = $('#MyGrid').data('kendoGrid');
var fieldName = grid.columns[e.container.index()].field;
var columnsToEdit = document.getElementById('EditableColumns').textContent;
var arrayOfColumns = columnsToEdit.split(",");
if (arrayOfColumns.indexOf(fieldName.toUpperCase()) < 0) {
$("#MyGrid").data("kendoGrid").closeCell(e.container);
}
}
</script>
Where "EditableColumns" label contains all columns names which should be editable.
I have a grid similar to the code below.
if an errors occurs on destroy action they accumulate.
for example the on the first error 1 call to destroy action, the second 2 calls, the third error 3 calls .......
after some investigation I found out that the items to be sleeted are stored in an array (_destroyed) in the dataSource,
so every time the destroy button is clicked the destroy action is called for each of these items.
I tried assigning null to the _destroyed array but this gave js error when I called destroy action again.
#(Html.Kendo().Grid<someType>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Name);
columns.Command(command =>
{
command.Edit();
command.Destroy();
}).Width(250);
})
.Editable(editable => { editable.Mode(GridEditMode.PopUp); editable.TemplateName("myTemplate"); })
.Pageable()
.Sortable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(50)
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(p => p.Id))
.Create(update => update.Action("EditingPopup_Create", "myController"))
.Read(read => read.Action("EditingPopup_Read", "myController"))
.Update(update => update.Action("EditingPopup_Update", "myController"))
.Destroy(update => update.Action("EditingPopup_Destroy", "myController"))
)
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
$(".k-grid").each(function () {
var grid = $(this).data("kendoGrid");
if (grid !== null && grid.dataSource == e.sender) {
grid.one('dataBinding', function (e) {
e.preventDefault();
});
grid.dataSource.read();
grid.refresh();
}
});
}
}
</script>
a
You can call the cancelChanges method of the data source and then read. There is no need to call grid.refresh() as it will be called automatically when dataSource.read() is done.
Ok I'm not sure If that's a legitimate answer but this fixed my problem
grid.dataSource._destroyed = [];
grid.dataSource.read();
grid.refresh();
I hope it saves some's time.
i have a Kendo grid that uses an edit Popup. The culture in the client is de-DE, when an user tries to edit a decimal number i.e. 8,5 Kendo sends a null to the server for that value and returns validation message "The value 8.5 is not valid for 'PropertyName'". Any help will be greatly appreciated.
#{
var culture = System.Globalization.CultureInfo.CurrentCulture.ToString();
}
<script src="#Url.Content("~/Scripts/Kendo/cultures/kendo.culture." + culture + ".min.js")"></script>
jQuery.extend(jQuery.validator.methods, {
date: function (value, element) {
return this.optional(element) || kendo.parseDate(value) != null;
},
number: function (value, element) {
return this.optional(element) || kendo.parseFloat(value) != null;
}
});
<script type="text/javascript">
kendo.culture("#culture");
</script>
#(Html.Kendo().Grid<SalesToolkit.ViewModels.AdminEquipDimViewModel.Equipment>()
.Name("grdEquipDim")
.Columns(columns =>
{
columns.Bound(dim => dim.EquipmentID).Width(50).Title("ID").Hidden(true);
columns.Bound(dim => dim.EquipmentName).Width(140).Title("Equipment Name");
columns.ForeignKey(dim => dim.EquipmentTypeID, (System.Collections.IEnumerable)ViewData["EquipTypes"], "EquipmentTypeID", "EquipmentName").Width(60).Title("Type");
columns.Bound(dim => dim.Metric).Width(55);
columns.Bound(dim => dim.ModelVerified).Width(65);
columns.Bound(dim => dim.LastModifiedBy).Width(130);
columns.Bound(dim => dim.TimeStamp).Format("{0:MM/dd/yyyy hh:mm:ss}").Width(120);
columns.Command(command => { command.Edit(); command.Destroy(); }).Width(160);
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Scrollable()
.HtmlAttributes(new { #class = "dimGrid" })
.Sortable()
.Pageable()
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Field(dim => dim.EquipmentID).Editable(false);
model.Field(dim => dim.TimeStamp).Editable(false);
model.Field(dim => dim.LastModifiedBy).Editable(false);
})
.Events(events => events.Error("error"))
.Model(model => model.Id(dim => dim.EquipmentID))
.Create(update => update.Action("EquipDim_Create", "AdminEquipDim", new { mID = Model.ManufacturerID }))
.Read(read => read.Action("EquipDim_Read", "AdminEquipDim", new { mID = Model.ManufacturerID }))
.Update(update => update.Action("EquipDim_Update", "AdminEquipDim"))
.Destroy(update => update.Action("EquipDim_Delete", "AdminEquipDim"))
)
)
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EquipDim_Update([DataSourceRequest] DataSourceRequest request, AdminEquipDimViewModel.Equipment equipMfg)
{
if (equipMfg != null && ModelState.IsValid)
{
AdminEquipDim oEquipMfg = new AdminEquipDim();
oEquipMfg.UpdateEquipDim(equipMfg);
}
return Json(ModelState.ToDataSourceResult());
}
From the samples and documentation, it looks like if I want to update one row (or do a batch update) in a Telerik grid, I also need to refresh the data in the entire grid.
Is there a way to just update that one row on the client and not return all the grid data every time I want to do an update? It seems extremely wasteful to keep returning that much data every time.
Even if I do a batch update, why do I need to return all the new data?
Generally a database has many users, and your user interface may be accessed by multiple people. If the grid is going to update, then it will include any other changes that may have happened to the data since the grid originally loaded.
The grid allows you to limit the number of records that are shown at a time via the paging option. On our project we are loading the grid with AJAX, and using IQueryable's in the controller. When we call ToDataSourceResult(request) on the IQueryable, it only retrieves the data that is needed, and does not load the full table from the database.
On the Razor View:
#(Html.Kendo().Grid<WebApp.ViewModels.AccountViewModel>()
.Name("Accounts")
.Columns(columns =>
{
columns.Bound(c => c.AccountNumber);
columns.Bound(c => c.Name);
columns.Bound(c => c.Address1);
columns.Bound(c => c.Address2);
columns.Bound(c => c.City);
columns.Bound(c => c.State);
columns.Bound(c => c.Zip);
columns.Bound(c => c.PrimaryContact).Title("Contact");
})
.Filterable(filterable => filterable
.Extra(false)
.Operators(operators => operators
.ForString(str => str.Clear()
.Contains("Contains")
.DoesNotContain("Doesn't Contain")
)
)
)
.Groupable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 5, 10, 20, 50, 100, 500 })
.ButtonCount(5)
)
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("Name").Ascending())
.PageSize(20)
.Read(read => read.Action("Account_Read", "Account"))
)
)
Then in the controller:
public ActionResult Account_Read([DataSourceRequest] DataSourceRequest request)
{
var jsonlist = GetAccounts()
.Select(sa => new AccountViewModel
{
ID = sa.ID,
AccountNumber = sa.AccountNumber,
Name = sa.Name,
Address1 = sa.Address1,
Address2 = sa.Address2,
City = sa.City,
State = sa.State,
Zip = sa.Zip,
PrimaryContact = sa.User.FirstName + " " + sa.User.LastName
}
).ToDataSourceResult(request);
return Json(jsonlist);
}
UPDATE
We have an inline edit form on one of our Kendo grids. It took us a bit to get it how we watned. In the Razor View:
#(Html.Kendo().Grid<DataViewModel>()
.Name("Data")
.Columns(columns =>
{
columns.Bound(c => c.FieldName)
.EditorTemplateName("DataFieldName")
.Title("Item Name")
.Width(200);
columns.Bound(c => c.TextValue)
.Title("Text");
columns.Command(command => { command.Edit(); command.Destroy(); })
.Title("Actions")
.Width(172);
})
.Filterable()
.Sortable()
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new int[] { 5, 10, 20, 50, 100 })
.ButtonCount(5)
)
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Sort(sort => sort.Add("CreatedDate").Descending())
.PageSize(20)
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(pd => pd.ID);
model.Field(pd => pd.CreatedDate).Editable(false);
model.Field(pd => pd.ValuesID).DefaultValue(Model.Values.ID);
})
.Read(read => read.Action("Data_Read", "History", new { ValuesID = Model.Values.ID }))
.Create(update => update.Action("Data_Create", "History"))
.Update(update => update.Action("Data_Update", "History"))
.Destroy(update => update.Action("Data_Destroy", "History"))
)
)
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function () {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>
In order to use the Kendo date time picker for the date option, we had to create a custom editor template. We created a new folder under Views >> Shared >> EditorTemplates. The file name is DataFieldName.cshtml:
#model WebApp.ViewModels.DataViewModel
#using WebApp.ViewModels
#(Html.Kendo().ComboBox()
.Name("FieldName")
.Placeholder("Select/Create Item Name")
.DataTextField("Name")
.DataValueField("Name")
.Filter(FilterType.Contains)
.DataSource(source => source
.Read(read => read.Action("GetFieldNames", "History"))
)
)
Then the controller has all of the action results for the AJAX calls:
[HttpPost]
public ActionResult Data_Create(DataViewModel DataIn)
{
var Data = new Data();
Data.ValuesID = DataIn.ValuesID;
Data.FieldName = DataIn.FieldName;
Data.TextValue = DataIn.TextValue;
if (DataIn.TimeValue != null) Data.TimeValue = DataIn.TimeValue;
if (ModelState.IsValid)
{
db.Datas.Add(Data);
db.SaveChanges();
}
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tankID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).TankID
});
}
[HttpPost]
public ActionResult Data_Update(DataViewModel DataIn)
{
var Data = db.Datas.Find(DataIn.ID);
Data.FieldName = DataIn.FieldName;
Data.TextValue = DataIn.TextValue;
if (DataIn.TimeValue != null) Data.TimeValue = DataIn.TimeValue;
if (ModelState.IsValid)
{
db.Entry(Data).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tkID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).tkID
});
}
[HttpPost]
public ActionResult Data_Destroy(DataViewModel DataIn)
{
var Data = db.Datas.Find(DataIn.ID);
db.Datas.Remove(Data);
db.SaveChanges();
return RedirectToAction("EditValue", new
{
ValueID = DataIn.ValuesID,
tkID = db.Values.FirstOrDefault(pv => pv.ID == DataIn.ValuesID).tkID
});
}
public ActionResult GetFieldNames()
{
var jsonList = db.Datas
.Select(pd => new
{
Name = pd.FieldName
})
.Distinct()
.OrderBy(pd => pd.Name)
.ToList();
return Json(jsonList, JsonRequestBehavior.AllowGet);
}
I have 2 telerik mvc ajax grids which needs to be populated based on the selected row on the first grid.
below is my code:
#(Html.Telerik().Grid<PurchaseRequest>()
.Name("grdPurchaseRequest")
.DataBinding(binding => binding.Ajax()
.Select("GetPurchaseRequests", "PurchaseOrder"))
.DataKeys(keys => keys
.Add(o => o.PurchaseRequestID))
.Columns(cols =>
{
cols.Bound(c => c.PurchaseRequestID).ReadOnly().Hidden();
cols.ForeignKey(c => c.ProjectID,(System.Collections.IEnumerable)ViewData["prProjects"],
"ProjectID", "ProjectName");
cols.Bound(c => c.FullName);
cols.Bound(c => c.RequestDate).Format("{0:MM/dd/yyyy}");
cols.Bound(c => c.Remarks);
cols.Bound(c => c.CheckedBy);
cols.Bound(c => c.ApprovedBy);
})
.ClientEvents(clientEvents => clientEvents.OnRowSelect("onRowSelected"))
.RowAction(row =>
{
row.Selected = row.DataItem.PurchaseRequestID.Equals(ViewData["id"]);
})
.Pageable()
.Sortable()
.Filterable()
.Selectable()
)
====Second GRID=====
This the the second Grid that will be populated based on the selected record on the first grid
#(Html.Telerik().Grid<PurchaseRequestDetail>().HtmlAttributes(new { style = "width: 50%" })
.Name("grdDetails")
.DataKeys(keys => keys
.Add(o => o.PurchaseRequestDetailID)
.RouteKey("PurchaseRequestDetailID"))
.Columns(cols =>
{
cols.ForeignKey(c => c.ItemID, (System.Collections.IEnumerable)ViewData["prItems"],
"ItemID", "ItemName").Width(200).Title("Description");
cols.Bound(d => d.ItemQuantity).Width(100).Title("Quantity");
cols.Bound(d => d.ItemValue).Width(100).Title("Value per quantity").Format("Php {0:###,###.00}");
cols.Bound(d => d.TotalPrice).Width(500).Format("Php {0:###,###.00}")
.Aggregate(aggs => aggs.Sum())
.ClientFooterTemplate("Php <#= $.telerik.formatString('{0:n}', Sum) #>");
})
.DataBinding(binding => binding.Ajax()
.Select("GetPurchaseRequestDetails", "PurchaseOrder", new { purchaseRequestID = "<#= PurchaseRequestID #>" }))
.ClientEvents(clientEvents => clientEvents.OnDataBinding("onDataBinding"))
.Pageable()
.Sortable()
)
the Script code
<script type="text/javascript">
var purchaseRequestID;
var purchaseRequestName;
function onRowSelected(e) {
var detailsGrid = $('#grdDetails').data('tGrid');
purchaseRequestID = e.row.cells[0].innerHTML;
purchaseRequestName = e.row.cells[1].innerHTML;
// update ui text
$('#purchaseRequestName').text(purchaseRequestName);
// rebind the related grid
//alert(purchaseRequestID);
//location.href = "/PurchaseOrder/Index/" + purchaseRequestID;
detailsGrid.rebind();
}
function onDataBinding(e) {
e.data = $.extend(e.data, { purchaseRequestID: purchaseRequestID });
}
below is the code in the controller:
[HttpPost]
public ActionResult Create(PurchaseOrder purchaseorder)
{
if (ModelState.IsValid)
{
HERE, I WANT TO BE ABLE TO GET AND SAVE THE SELECTED ROW IN THE VIEW
//purchaseorder.PurchaseRequestID = ViewBag.SelectedID;
db.PurchaseOrders.Add(purchaseorder);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.SupplierID = new SelectList(db.Suppliers, "SupplierID", "Name", purchaseorder.SupplierID);
ViewBag.OfficeID = new SelectList(db.Offices, "OfficeID", "OfficeName", purchaseorder.OfficeID);
return View(purchaseorder);
}
Thanks
In case some of you might encounter the same problem,
I used the HiddenFor to solve this. Please suggest if you have a better way than this.
#Html.HiddenFor(model => model.PurchaseRequestID)
and then i updated the script
<script type="text/javascript">
var purchaseRequestID;
var purchaseRequestName;
function onRowSelected(e) {
var detailsGrid = $('#grdDetails').data('tGrid');
purchaseRequestID = e.row.cells[0].innerHTML;
purchaseRequestName = e.row.cells[1].innerHTML;
// update ui text
$('#purchaseRequestName').text(purchaseRequestName);
$('#PurchaseRequestID').val(purchaseRequestID);
detailsGrid.rebind();
}
function onDataBinding(e) {
e.data = $.extend(e.data, { purchaseRequestID: purchaseRequestID });
}