Crud operation Of kendo ui Grid using json - c#

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);
}

Related

get data from webservice method for kendo grid

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"
}
]
});
});

grid multiselect post data binding issue

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!

Kendo Grid - Custom Command to Enable row in Edit

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>

JSON returned from ASP.NET does not bind with Kendo grid

I can successfully make the AJAX call to my web method using the following code and web method return the JSON which is pasted below:
My Web Method
[WebMethod]
public static string GetJson()
{
string query = "SELECT top 10 cast(ClientUID as varchar) ClientUID FROM <tablename>";
SqlCommand cmd = new SqlCommand(query);
// Populate the DataSet.
DataSet data = GetData(cmd);
// return the Customers table as JSON.
DataTable dt = data.Tables[0];
var returnJSON = (from p in dt.AsEnumerable()
select new
{
ClientUID = p.Field<string>("ClientUID")
}).ToList();
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(returnJSON);
return json;
}
JSON returned by web method:
[{"ClientUID":"1"},{"ClientUID":"2"},{"ClientUID":"3"},{"ClientUID":"4"},{"ClientUID":"5"},{"ClientUID":"6"},{"ClientUID":"7"},{"ClientUID":"8"},{"ClientUID":"9"},{"ClientUID":"10"}]
Call to web method using AJAX
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
data: msg.d,
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Problem : My grid does not bind and only headers are displayed whereas when I use the code in this manner mentioned below it is working
<script type="text/javascript">
$(document).ready(function() {
$.ajax(
{
type: "POST",
url: "ServeClientCalls.aspx/GetJson",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
//checking the content return from the above web method
$("#msg").html(msg.d);
**var p = [{ ClientUID: 1 }, { ClientUID: 2 }, { ClientUID: 3 }, { ClientUID: 4 }, { ClientUID: 5 }, { ClientUID: 6 }
, { ClientUID: 7 }, { ClientUID: 8 }
, { ClientUID: 9 }, { ClientUID: 10}];**
//Binding to kendo Grid
$("#grid").kendoGrid({
dataSource: {
**data: p,**
schema: {
model: {
fields: {
ClientUID: { type: "string" }
}
}
},
pageSize: 20
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [
{ field: "ClientUID" }
]
});
},
error: function(x, e) {
$("#msg").html(x.responseText);
}
});
});
</script>
Use data: "d", under schema section. That should work.

Inline edit in Kendo UI grid?

The cancel button still exists and the update button never changes back to edit in Kendo UI grid after the ajax call to server?! I guess I have to notify the grid that the update has done, but how ?
<div id="mykendoGrid">
<script>
$(document).ready(function () {
var MydataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: "/_layouts/AjaxCallHandler/Handler.ashx",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
//data: options.data,
success: function (data) {
//ko.mapping.fromJS(data, self.seats);
options.success(data);
}
});
},
update: function (options) {
$.ajax(
{
type: 'POST',
url: "/_layouts/AjaxCallHandler/Handler.ashx",
data: { 'currency': ko.mapping.toJSON(options.data) },
success: function (response)
{
// do nothing
alert("Successfully Saved.");
},
error: function (repsonse) {
alert("Manage: UpdateReportName -> Ajax Error!");
}
});
return;
}
//parameterMap: function (data, operation) {
// if (operation !== "read") {
// return JSON.stringify({ currency: data })
// //return ko.mapping.fromJS(data, self.seats);
// }
//}
},
batch: false,
pageSize: 10,
schema: {
//data: 'd',
model:
{
id: "ID",
fields:
{
ID: { editable: false, nullable: false },
DisplayName: { editable: true },
Code: { editable: true }
}
}
}
})
$("#mykendoGrid").kendoGrid({
dataSource: MydataSource,
pageable: true,
toolbar: ["create"],
columns: [{ field: "ID", title: "ID" }, { field: "DisplayName", title: "Display Name" }, { field: "Code", title: "Code" }, { command: ["edit"], title: " ", width: "250px" }],
editable: "inline",
scrollable: true
});
});
</script>
</div>
You need to call options.success();
update: function (options) {
$.ajax(
{
type: 'POST',
url: "/_layouts/AjaxCallHandler/Handler.ashx",
data: { 'currency': ko.mapping.toJSON(options.data) },
success: function (response)
{
// do nothing
alert("Successfully Saved.");
options.success();
//or
//options.success(reponse);
},
error: function (response) {
alert("Manage: UpdateReportName -> Ajax Error!");
options.error();
//or
//options.error(reponse);
}
});
return;
}
You need to call yourGrid.saveChanges(); from your JavaScript. This will iterate through each row actioning the necessary create, update and destroy commands for your grids datasource and all your edits will be saved.

Categories

Resources