I have a Kendo Grid that uses Inline Editing. Instead of using the standard Edit() command that is available within the Kendo Framework, I would like to have a kendo Custom Command that when clicked it finds the current row and puts that row in edit mode.
This grid also appends a new row to the bottom of the grid.
Note: I am trying to simulate batch editing client side.
Please follow this example :
<body>
<h1>Kendo Grid</h1>
<hr />
<div id="Correspondence"></div>
<input type="hidden" id="hdnEmployeeId" />
<script>
//Parent grid
$(document).ready(function () {
var element = $("#Correspondence").kendoGrid({
dataSource: {
data: #Html.Raw(Json.Encode(Model)),
editable: { destroy: true },
batch: true,
pageSize: 5,
schema: {
model: {
id: "EmployeeId",
fields: {
EmployeeId: { type: "number" },
Name: { type: "string" },
Gender: { type: "string" },
City: { type: "string" }
}
}
}
},
height: 430,
sortable: true,
pageable: true,
selectable: true,
detailInit: detailInit,
dataBound: function () {
this.expandRow(this.tbody.find("tr.k-master-row").first());
},
columns:
[
{ field: "EmployeeId", title: "EmployeeId", width: "110px" },
{ field: "Name", title: "Name", width: "110px" },
{ field: "Gender",title: "Gender", width: "110px" },
{ field: "City",title: "City", width: "110px" },
],
change: function () {
//Get the selected row id
alert("EmployeeId "+ this.dataItem(this.select()).EmployeeId);
}
});
//you can expand it programatically using the expandRow like this
element.on('click', 'tr', function () {
$(element).data().kendoGrid.expandRow($(this));
})
//Child grid
function detailInit(e) {
$("<div/>").appendTo(e.detailCell).kendoGrid({
dataSource: {
data: #Html.Raw(Json.Encode(Model)),
editable: { destroy: true },
batch: true,
pageSize: 5,
schema: {
model: {
id: "EmployeeId",
fields: {
EmployeeId: { type: "number" },
Name: { type: "string" },
Gender: { type: "string" },
City: { type: "string" }
}
}
}
},
scrollable: false,
sortable: false,
selectable: true,
pageable: true,
columns:
[
{ field: "EmployeeId", title: "EmployeeId", width: "110px" },
{ field: "Name", title: "Name", width: "110px" },
{ field: "Gender",title: "Gender", width: "110px" },
{ field: "City",title: "City", width: "110px" },
]
}).data("kendoGrid");
}
}); // end ready
</script>
</body>
Related
i want get data from webservice method and fill my kendo grid.
my method run and get data but when fill kendo grid show this error:
https://image.ibb.co/jNJB4a/asfasfas.png
my code in web method:
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
public string TierPriceListWithProduct(string ID)
{
BOProduct boProduct = new BOProduct();
boProduct.Id = Convert.ToInt32(ID);
string Result = "";
if (boProduct != null)
{
try
{
IList<DAOTierPrice> daoTierPriceCollection = DAOTierPrice.SelectAllByProductId(boProduct.Id);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string result = serializer.Serialize(daoTierPriceCollection);
Result = result;
}
catch (Exception ex)
{
Result = "Faild#SystemError#reson#" + ex.Message;
}
}
return Result;
}
And code from client:
$(document).ready(function () {
var ID = getUrlVars()["ID"];
var BOProduct = {};
BOProduct.Id = ID;
var data = JSON.stringify(BOProduct);
//AjaxFunctionsAdminPages.asmx / TierPriceListWithProduct",
$("#tierprices-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "../../AjaxFunctionsAdminPages.asmx/TierPriceListWithProduct",
type: "POST",
dataType: "json",
data: {
ID: ID
}
},
destroy: {
url: "/Admin/Product/TierPriceDelete",
type: "POST",
dataType: "json",
data: addAntiForgeryToken
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
Store: { editable: true, type: "string" },
StoreId: { editable: true, type: "number" },
CustomerRole: { editable: true, type: "string" },
CustomerRoleId: { editable: true, type: "number" },
Quantity: { editable: true, type: "number" },
Price: { editable: true, type: "number" },
StartDateTimeUtc: { editable: true, type: "date" },
EndDateTimeUtc: { editable: true, type: "date" },
Id: { editable: false, type: "number" }
}
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
}
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false
},
editable: {
confirmation: "hhhhhh",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "StoreId",
hidden: true,
title: "Store",
template: "#:Store#"
}, {
field: "CustomerRoleId",
title: "Customer",
template: "#:CustomerRole#"
}, {
field: "Quantity",
title: "Quantity",
format: "{0:0}"
}, {
field: "Price",
title: "Price"
}, {
field: "StartDateTimeUtc",
title: "astartdatetimeutc",
type: "date",
format: "{0:G}"
}, {
field: "EndDateTimeUtc",
title: "enddatetimeutc",
type: "date",
format: "{0:G}"
}, {
field: "Id",
title: "Edit",
headerAttributes: { style: "text-align:center" },
attributes: { style: "text-align:center" },
template: "<button onclick=\"javascript:OpenWindow('/Admin/Product/TierPriceEditPopup/#=Id#?btnId=btnRefreshTierPrices&formId=product-form', 800, 600, true); return false;\" class='btn btn-default'><i class='fa fa-pencil'></i>Edit</button>"
}, {
command: { name: "destroy", text: "Delete" },
title: "Delete"
}
]
});
});
I want a kendo UI MVC 4 or 5 c# Grid with Add,Edit,Delete using ajax json and Sqlserver demo curd opeartion.
Any one can help me out..
Here i am using a simple method but it is not working properly..
<script>
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetAllUsers","Task")",
dataType: "json"
},
update: {
url: "#Url.Action("Edit","Task")",
dataType: "json",
contentType: "application/json;charset=utf-8",
type:"POST"
},
destroy: {
url: "#Url.Action("Delete","Task")",
dataType: "json",
contentType: "application/json;charset=utf-8",
type:"POST"
},
parameterMap: function(data,type)
{
return kendo.stringify(data.models);
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { editable: false },
UserName: { type: "string" },
FirstName: { type: "string" },
LastName: { type: "string" },
Address: { type: "string" },
IsActive: { type: "boolean" },
DateCreated: { type: "date" }
}
}
},
batch: true,
pageSize: 20,
});
$("#allUsers").kendoGrid({
dataSource:dataSource,
height: 550,
groupable: true,
sortable: true,
navigatable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{ field: "UserName",title: "User Name" },
{ field: "FirstName",title: "First Name" },
{ field: "LastName",title: "Last Name" },
{ field: "Address",title: "Address" },
{ field: "IsActive",title: "Active" },
{ field: "DateCreated",title: "Join Date",format: "{0:dd-MM-yyyy}" },
{ command: "destroy" }
],
toolbar: ["save","cancel"],
editable: {
mode: "incell",
update: true,
destroy: true,
confirmation:true
},
edit: function (event) {
console.log("at edit event");
},
save: function(event)
{
console.log("at saveChanges event");
},
});
});
</script>
So any one can guide me??
Don't send me the link of telerik website..just give me a solutions or code..
You can use this Kendo Grid Html Sample;
<!-- BEGIN KendoGrid -->
<div>
#(Html.Kendo().Grid<SampleViewModel>()
.Name("KendoGrid")
.Scrollable()
.Columns(columns =>
{
columns.Bound("").HtmlAttributes(new { style = "text-align:center;" }).ClientTemplate("<a class='k-button' onclick=\"deleteSample(#=Id#)\"><span class='k-icon k-delete'></span>Delete</a>").Width(85).Sortable(false);
columns.Bound("").HtmlAttributes(new { style = "text-align:center;" }).ClientTemplate("<a class='k-button' href=\"/Sample/Edit/#= Id #\"><span class='k-icon k-edit'></span>Edit</a>").Width(130).Sortable(false);
columns.Bound(x => x.Name);
columns.Bound(x => x.Code);
columns.Bound(x => x.Regex);
columns.Bound(x => x.StatusText);
})
.Pageable(pager => pager
.Input(true)
.Numeric(false)
.Info(true)
.PreviousNext(true)
.Refresh(true))
.Scrollable()
.Sortable()
.HtmlAttributes(new { style = "height:480px;" })
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.ServerOperation(true)
.Read(read => read.Action("GetSampleList", "Sample"))
))
</div>
<!-- END KendoGrid -->
Delete button will open the popup if you want.
Edit button will be open the edit page.
public ActionResult Edit(int id)
{
var model = x.GetById(id);
return View(model);
}
And GetSampleList; (It is already json)
public JsonResult GetSampleList()
{
var list = x.GetSampleList();
return Json(list, JsonRequestBehavior.AllowGet);
}
I'm building a Kendo UI Grid using their JS library. This is the code im using:
<div>
<div>
<div id="grid"></div>
<script>
$(document).ready(function () {
var Supplier = kendo.data.Model.define({
id: "SupplierId",
fields: {
SupplierId: { required : true},
PrefixCountryCode: { required: true },
SupplierName: { required: true }
}
});
var customer = kendo.data.Model.define({
id: "CustomerId",
fields: {
CustomerId: { editable: false },
CustomerName: { validation: { required: true } },
CountryCode: { validation: { required: true } },
CustomerERPId: { validation: { required: true } },
Suppliers: {
}
}
});
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetCustomers", "Customer")',
dataType: "json"
},
update: {
url: '#Url.Action("SaveCustomer", "Customer")',
dataType: "json",
type: "POST"
},
destroy: {
url: '#Url.Action("RemoveCustomer", "Customer")',
dataType: "json",
type: "POST"
},
create: {
url: '#Url.Action("CreateCustomer", "Customer")',
dataType: "json",
type: "POST"
},
parameterMap: function (options, operation) {
if (operation !== "read") {
console.log(options);
return options;
}
}
},
pageSize: 20,
schema: {
model: customer
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create"],
columns: [
{
field: "CustomerName",
title: "CustomerName",
width: 200
}, {
field: "CountryCode",
title: "CountryCode",
width: 50
},
{
field: "CustomerERPId",
title: "CustomerERPId",
width: 100
},
{
field: "Suppliers",
title: "Suppliers",
width: 200,
editor: supplierMultiSelect, template: kendo.template($("#supplierTemplate").html())
},
{ command: ["edit", "destroy"], title: " ", width: "200px" }
],
editable: "inline",
});
});
function supplierMultiSelect(container, options) {
console.log(options.field);
$('<input data-text-field="SupplierName" data-value-field="SupplierId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoMultiSelect({
autoBind: true,
dataTextField: "SupplierName",
dataValueField: "SupplierId",
dataSource: {
type: "json",
transport: {
read: {
url: '#Url.Action("GetSuppliers", "Customer")',
dataType: "json"
}
}
},
});
}
</script>
<script type="text/kendo" id="supplierTemplate">
<ul>
#for(var i = 0; i< Suppliers.length; i++){#
<li>#:Suppliers[i].SupplierName#</li>
#}#
</ul>
</script>
</div>
As you can see i have an kendo multiselect in each row. The problem i got is that when i try to update the values the values from the multiselect doesn't follow along to the controller. In the parameterMap method i have a console log and there i can see that all the values that the grid post to the controller is correct.
The image above is from my chrome console and there i have 3 multiselect models that exists in the object and that is correct.
On the image above you can see what my controller method gets from the post.
It gets all the values from the customer-object and it also gets that there is 3 suppliers to the customer that got posted. But all the values for each of the suppliers is null. I guess this has to something to do with the binding of the multiselect but i just can't figure out why it doesn't work. Plz help!
I am using jqgrid 4.4's inlineNav functionality to provide Add/Edit capability for my subgrid. However I cannot figure out how to get the Add event to be called. Only the Update event is called when I "Add" the record.
I also don't know how to get the row_id from the parent grid row into the subgrid so that I can pass it to the Add event.
Here is my code
<script type="text/javascript">
$(document).ready(function () {
$('#jqgFactors').jqGrid({
//url from wich data should be requested
url: '#Url.Action("GetFactors")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['id', 'category', 'question type', 'question', 'tooltip text', 'xdata', 'warningexception'],
//columns model
colModel: [
{ name: 'id', index: 'id', align: 'left', editable: false, width: '40px', fixed: true, key: true },
{ name: 'categoryid', index: 'categoryid', align: 'left', editable: true, edittype: 'select', width: '80px', fixed: true, editoptions: { value: { 1: 'Departure', 2: 'Pilot', 3: 'Product', 4: 'Flight', 5: 'Destination'} }, editrules: { required: true} },
{ name: 'type', index: 'type', align: 'left', editable: true, edittype: 'select', width: '100px', fixed: true, editoptions: { value: { 1: 'RadioButton List', 2: 'DatePicker'} }, editrules: { required: true} },
{ name: 'questiontext', index: 'questiontext', align: 'left', editable: true, edittype: 'textarea', width: '200px', fixed: true, editoptions: { rows: '5', cols: '40' }, editrules: { required: true} },
{ name: 'tooltip', index: 'tooltip', align: 'left', editable: true, edittype: 'textarea', width: '300px', fixed: true, editoptions: { rows: '5', cols: '40' }, editrules: { required: true} },
{ name: 'x', index: 'x', align: 'left', editable: true, edittype: 'select', width: '60px', fixed: true, editoptions: { value: { 1: 'true', 0: 'false'} }, editrules: { required: true} },
{ name: 'warningexception', index: 'warningexception', align: 'left', editable: true, edittype: 'select', width: '60px', editoptions: { value: { 1: 'true', 0: 'false'} }, editrules: { required: true} }
],
//pager for grid
pager: $('#jqgpFactors'),
rowNum: 60,
sortname: 'id',
sortorder: 'asc',
viewrecords: true,
height: '100%',
width: 900,
subGrid: true,
subGridRowExpanded: function (subgrid_id, row_id) {
var subgrid_table_id;
var subgrid_pager_id;
subgrid_table_id = subgrid_id + "_t";
subgrid_pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("<table id='" + subgrid_table_id + "' class='scroll'></table><div id='" + subgrid_pager_id + "' class='scroll'></div>");
$("#" + subgrid_table_id).jqGrid({
url: '#Url.Action("GetFactorDetails")',
postData: { QuestionId: function () { return row_id; } },
datatype: "json",
mtype: "POST",
colNames: ['id', 'questionid', 'text', 'influence', 'weight'],
colModel: [
{ name: "id", index: "id", key: true, hidden: true },
{ name: "questionid", index: "questionid", hidden: true },
{ name: "text", index: "text", width: 700, editable: true, edittype: 'text' },
{ name: "influence", index: "influence", width: 80, editable: true, edittype: 'text', editrules: { required: true, integer: true} },
{ name: "weight", index: "weight", sortable: false, width: 80, editable: true, edittype: 'text', editrules: { required: true, integer: true} }
],
height: '100%',
rowNum: 5,
sortname: 'id',
sortorder: 'asc',
pager: subgrid_pager_id,
editurl: 'clientArray',
width: 860
});
$("#" + subgrid_table_id).jqGrid('navGrid', '#' + subgrid_pager_id, { edit: false, add: false, del: false });
$("#" + subgrid_table_id).jqGrid('inlineNav', '#' + subgrid_pager_id, {
addParams: {
addRowParams: {
keys: true,
url: '#Url.Action("AddFactorDetail")'
}
},
editParams: {
url: '#Url.Action("UpdateFactorDetail")'
},
add: true,
edit: true,
save: true,
cancel: true
}
});
}
});
$.jgrid.nav.addtext = "Add Record";
$.jgrid.nav.edittext = "Edit Record";
$.jgrid.nav.deltext = "Delete Record";
$('#jqgFactors').jqGrid('navGrid', '#jqgpFactors',
{ add: true, del: true, edit: true, search: false },
{ width: 'auto', url: '#Url.Action("UpdateFactor")' },
{ width: 'auto', url: '#Url.Action("UpdateFactor")' }, //insert
{ width: 'auto', url: '#Url.Action("DeleteFactor")' });
$('#dlgFactor').dialog({ autoOpen: false, bgiframe: true, resizable: false, title: 'Factor' });
$('a[data-supplier-id]').live('click', function (e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
var dialogPosition = $(this).offset();
$.post('#Url.Action("Factor")', { FactorId: $(this).attr('data-supplier-id') }, function (data) {
$('#dlgFactor').empty();
$('#tmplFactor').tmpl(data).appendTo('#dlgFactor');
$('#dlgFactor').dialog('option', 'position', [dialogPosition.left, dialogPosition.top]);
$('#dlgFactor').dialog('open');
});
});
});
This is what I want the control to look like: Update is working fine.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateFactorDetail(FactorDetailModel model, int Id)
{
model.QuestionId = Id;
FactorManager fm = new FactorManager();
return Json(fm.UpdateDetail(model));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddFactorDetail(FactorDetailModel model, int QuestionId)
{
model.QuestionId = QuestionId;
FactorManager fm = new FactorManager();
return Json(fm.AddDetail(model));
}
Am not sure about your first question but to your second question, i think the following links will help you..
wiki-subgrid events-check example
Rick and Eric's answer - i assume you already know this as you have edited the post.
access parent grid id
Hope it helps.
everything is working fine with my jqgrid except a small issue. i have defined postData below:
$(document).ready(function() {
$("#ctl00_ContentPlaceHolder2_drpUSite").change(function() {
site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val());
loadusergrid();
});
var usrparams = new Object();
var site = ($("#ctl00_ContentPlaceHolder2_drpUSite").val());
//----grid code---------
$("#users").jqGrid({
prmNames: {
_search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: { searchString: '', searchField: '', searchOper: '', sites: site },
datatype: function(postdata) {
mtype: "GET",
$.ajax({
url: 'Users.aspx/GetUsers',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data, st) {
if (st == "success") {
var grid = $("#users")[0];
var m = JSON.parse(data.d);
grid.addJSONData(m);
}
},
error: function() {
alert("Loading Failed!");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
cell: "cell",
id: "login",
repeatitems: true
},
colNames: ['Login', 'First Name', 'Last Name', 'Email', 'Site', 'Role', 'Room', 'UnitID', 'Supervisor', 'Super'],
colModel: [
{ name: 'login', index: 'login', width: 20 },
{ name: 'fname', index: 'fname', width: 20, hidden: true },
{ name: 'lname', index: 'lname', width: 60, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'email', index: 'email', width: 20, align: "center", sortable: false },
{ name: 'site', index: 'site', width: 50, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'role', index: 'role', width: 15, align: "center", sortable: true, searchoptions: { sopt: ['eq', 'ne']} },
{ name: 'room', index: 'room', width: 30, align: "center", sortable: true },
{ name: 'unitid', index: 'unitid', width: 10, align: "center", sortable: false },
{ name: 'super', index: 'super', width: 20 },
{ name: 'supername', index: 'supername', width: 10, align: "center", sortable: false },
],
pager: "#pageusers",
viewrecords: true,
caption: "Registered Users",
imgpath: 'themes/steel/images',
rowNum: 20,
rowList: [10, 20, 30, 40, 50],
sortname: "pname",
sortorder: "desc",
showpage: true,
gridModel: true, gridToolbar: true,
onSelectRow: function(id) {
var ret = jQuery("#users").getRowData(id);
accpara.id = ret.id;
accpara.pname = ret.pname;
accpara.pid = ret.pid;
accpara.bld = ret.bld;
accpara.cname = ret.cname;
accpara.amt = ret.amt;
accpara.status = ret.status;
accpara.notes = ret.notes;
accpara.lname = ret.lname;
}
});
jQuery("#users").navGrid('#pageusers', { view: false, del: false, add: false, edit: false },
{}, // default settings for edit
{}, // default settings for add
{}, // delete
{closeOnEscape: true, multipleSearch: true,
closeAfterSearch: true
}, // search options
{}
);
$("#users").setGridWidth(1300, true);
$("#users").setGridHeight(500, true);
jQuery("#users").jqGrid('filterToolbar');
//----grid code ends here
function loadusergrid() {
$("#users").setGridParam({ page: 1 }, { pgbuttons: true }, { pginput: true }, { postData: { "site": site} }).trigger("reloadGrid");
}
});
when page loads for the 1st time, this works..
now i have 4 drop-downs which filter users. i have written a function which reloads the grid when the dropdown is changed, but it isnt working.. what am i doing wrong here?? when i enable postback for the dropdowns, i get the filtered result. i want to avoid postbacks on my page :). right now i have added just the site dropdown as the filter. once this starts working ill add the remaining 3.
firebug shows the ajax call is fired successfully but with an empty sitename. please note that the site dropdown cntains an empty value when page is loaded for the 1st time.
thanks in advance
$("#mygrid").setPostData({parameters}); does the trick