Call knockout method inside kendo grid - asp.net-mvc

I have simple kendo UI grid
$("#Grid").kendoGrid({
dataSource: {
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
the problem is when I am using:
data-bind="click:Edit(#: Id#)"
when click on edit calling function not work inside kendo grid notice that both the grid and function inside knockout viewmodel
function viewmodel() {
var self = this;
self.Load = function () {
$("#Grid").kendoGrid({
dataSource: {
type: "aspnetmvc-ajax",
serverPaging: true,
transport: {
read: "Course/Read",
dataType: "json"
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
pageSize: 10
},
pageable: true,
columns:
[
{ field: "CourseName", title: "Name", width: 100 },
{ field: "SpecialtyName", title: "Specialty", width: 100, filterable: false },
{ title: "Edit", template: '<span class="EditIcon"><i data-bind="click:Edit(#: Id#)" class="fa fa-edit"></i></span>', width: 50 },
]
});
}
self.Load();
self.Edit= function (Id) {
////////my code////////
}
}
everything work fine the binding retrieve data, extra except call knockout method inside kendo grid, appreciate any help thanks.

if anyone looking for answer or open this post, this is not related to kendo, this is because the grid render rows after knockout binding done, so you can take viewmodel object in temp var in javascript and use it like tempvar.callfunction().

Related

in jqgrid : I want to show an empty grid with no pagination and display a message "no records found" if no records

I need to show an empty grid with no pagination and display a message "You have no records found" if empty results in jqGrid.i'm pretty new to this jqgrid.
I have added the code as below. Please Find the Oleg Demo1, Demo2
$(function () {
var $grid = $("#oversight-sample"),
//mydata = [{actions: "a", url: "http://stackoverflow.com/q/24609566/315935", created: "7/7/2014"}];
mydata = [];
emptyMsgDiv = $("<div><span style='color:red;font-size:24px'>You have no records found</span></div>");
$grid.jqGrid({
//autowidth: true,
caption: "Evaluated URLs",
colNames: ["Actions", "URL", "Fetch Date"],
colModel: [
{ name: "actions", align: "center", title: false, width: 60, resizable: false, sortable: false },
{ name: "url", width: 400 },
{ name: "created", align: "center", width: 125, sorttype: "date" }
],
data: mydata,
datatype: "local",
emptyrecords: "0 records found",
localReader: {
page: function (obj) {
return (obj.page === 0 || obj.page === undefined) ? "0" : obj.page;
}
},
loadComplete: function () {
var ts = this;
if (ts.p.reccount === 0) {
$(this).hide();
emptyMsgDiv.show();
} else {
$(this).show();
emptyMsgDiv.hide();
}
},
height: "auto",
sortname: "created",
toppager: true,
pager: "#url-pager",
viewrecords: true
});
// place div with empty message insde of bdiv
emptyMsgDiv.insertAfter($grid.parent());
});
<table id="oversight-sample"><tbody><tr><td></td></tr></tbody></table>
<div id="url-pager"></div>
Here is the link to fiddler with the 'No records found' message. I hope it will give you an idea on how to create a basic jqgrid and what library references are required.
https://jsfiddle.net/99x50s2s/2/
<table id="sg1"></table>
<div id="psg1"></div>
jQuery("#sg1").jqGrid({
datatype: "local",
gridview: true,
loadonce: true,
shrinkToFit: false,
autoencode: true,
height: 'auto',
viewrecords: true,
sortorder: "desc",
scrollrows: true,
loadui: 'disable',
emptyrecords: 'No records found',
pager: '#psg1',
colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],
colModel:[
{name:'id',index:'id', width:60, sorttype:"int"},
{name:'invdate',index:'invdate', width:90, sorttype:"date"},
{name:'name',index:'name', width:80},
{name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},
{name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},
{name:'total',index:'total', width:80,align:"right",sorttype:"float"},
{name:'note',index:'note', width:150, sortable:false}
],
caption: "Test Grid"
});
var mydata = [];//pass empty data
for(var i=0;i<=mydata.length;i++)
jQuery("#sg1").jqGrid('addRowData',i+1,mydata[i]);

Kendo grid sending date in wrong format

it is kendoui grid working against webapi (.net mvc 4 project)
the kendoGrid part in my js file:
$("#eventsgrid").kendoGrid({
dataSource: {
transport: {
read: { url: "/Webapi/V2/.../events", type: "GET" },
update: { url: "/Webapi/V2/.../events", type: "PUT" },
create: { url: "/Webapi/V2/.../events", type: "POST" },
destroy: { url: "/Webapi/V2/.../events", type: "DELETE" }
},
pageSize: 10,
schema: {
model: {
id: "eventId",
fields: {
eventId: { type: "number", editable: false, nullable: true },
eventCode: { type: "string" },
eventLocation: { type: "string" },
clientId:{ type: "string" },
startDate:{ type: "date" },
endDate: { type: "date" }
}
}
}
},
columns: [
{ field: 'eventId', title: 'ID', width: '50px', filterable: true },
{ field: 'eventCode', title: 'Code', width: '80px', filterable: true },
{ field: 'eventLocation', title: 'Location', width: '150px', filterable: true },
{ field: 'clientId', title: 'Client', width: '80px', filterable: true },
{ field: 'startDate', title: 'Start', width: '80px', format: "{0:MM/dd/yyyy}", filterable: { ui: "datepicker" } },
{ field: 'endDate', title: 'End', width: '80px', format: "{0:MM/dd/yyyy}", filterable: { ui: "datepicker" } },
{ command: [{ id: "edit", name: "edit", text: "Edit" }, { id: "destroy", name: "destroy", text: "Delete", width: "30px" }, { text: 'Details', click: gotouser }], title: "&nbsp", width: "240px" }
],
sortable: true,
editable: "popup",
filterable: {
extra: false,
operators: {
string: {
startswith: "Starts with",
eq: "Is equal to",
neq: "Is not equal to"
}
}
},
toolbar: [{ name: "create", text: "Add new Event" }],
pageable: { pageSizes: true | [10, 20, 30] }
});
the problem is: when i edit a record, or post a new one, the value i receive in my mvc controller for any of the date fields, is null.
when i check in my chrome tools, see what the grid sends to the controller (when you hit update in the popup), like this:
clientId: 1
startDate: Tue Jan 20 2015 00:00:00 GMT-0500 (Eastern Standard Time)
endDate: Thu Jan 22 2015 00:00:00 GMT-0500 (Eastern Standard Time)
logo: abcsd.jpg
featured: 4
obviously the date format is wrong, and i suppose that is why the controller does not see it as a date, the conversion/binding fails, and it gives me null.
How do i make it send a different format, like mm/dd/yyyy ? isn't that covered by the format definitions in the columns array?
You can try to use parameterMap function. Look at kendo parameterMap documentation.
Similar to this:
parameterMap: function (data, operation) {
if (operation != "read") {
var parsedDate = kendo.parseDate(data.startDate, "MM/dd/yyyy");;
data.startDate = parsedDate;
return data;
}
}
For kendo parsing dates look at kendo parseDate
in the parameterMap use:
var parsedDate = kendo.toString(data.startDate, "MM/dd/yyyy")
the kendo.parseDate function takes a string as a parameter
OK, I followed Dmitriy's line, and was able to make it work. so for future generations, here is what you need to add to your js:
update: {
url: "/Webapi/..../events",
dataType: "json",
type: "PUT",
data: function (data) {
data.startDate = kendo.toString(data.startDate, "yyyy-MM-dd");
data.endDate = kendo.toString(data.endDate, "yyyy-MM-dd");
// repeat for all your date fields
return data;
}
},
// same thing for your 'create'.
// Sorry, look like a bit of 'Repeat yourself', but at least it's working.
So again, big thanks to Dimitriy!

Kendo UI Grid Update button not firing

I am developing a KendoUI Grid with Inline editable option in javascript and can't make Update button to fire click event and post the data to server side update event. Clicking on Update button won't even update the grid on client.
Hope someone can help me point out what I am doing wrong here.
This is not a duplicate to this as I have tired the jfiddle link in the answer and it is not working too.
kendo UI grid update function wont fire
<div id="grid"></div>
#section Scripts{
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "Home/GetPupilsAsJson",
dataType: 'json'
},
update: {
url: "Home/UpdatePupils",
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
$('#grid').kendoGrid({
dataSource: dataSource,
editable: "inline",
pageable: true,
columns: [{
field: "Id",
title: "Id",
width: 150,
hidden: true
}, {
field: "Firstname",
title: "Firstname",
width: 150
}, {
field: "Lastname",
title: "Lastname",
width: 150
}, {
field: "DateOfBirth",
title: "DateOfBirth",
width: 150
}, {
field: "Class",
title: "Class",
width: 150
}, {
field: "Year",
title: "Year",
width: 150
},
{
command: ["edit"],
width: 150
}]
});
});
</script>
}
HomeController
public ActionResult GetPupilsAsJson()
{
return Json(GetPupils(), JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
[HttpPost]
public void UpdatePupils(Pupil p)
{
//never reach here
}
I don't know why but fixed it by putting schema information.
schema: {
model: {
id: "Id",
fields: {
Firstname: { editable: true, validation: { required: true } },
Lastname: { validation: { required: true } },
DateOfBirth: { validation: { required: true } },
Class: { validation: { required: true } },
Year: { validation: { required: true } }
}
}
}
Use #Url.Action("GetPupilsAsJson", "Home")' so no need to pass base url in your update action like this BASEURL+ "Home/GetPupilsAsJson".
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',
dataType: 'json'
},
update: {
url:'#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
}
},
pageSize: 5,
autoSync: true
});
use parameter map to pass model values
<script type="text/javascript">
$(function () {
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("GetPupilsAsJson", "Home")',,
dataType: 'json'
},
update: {
url: '#Url.Action("UpdatePupils", "Home")',
dataType: 'json',
type: 'POST'
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
pageSize: 5,
autoSync: true
});
Call Controller with parameterMap
public JsonResult UpdatePupils(string models)
{
return Json(..);
}
Is any of your cell text has HTML tags like < or >, remove them and click on update. The update event will fire.

JQWidgets jqxGrid: Dataadapter and Paging

i have a newbie question, but i’m scratching my head on this one. I have a grid, bound to a dataadapter. On the grid, paging and filtering is explicit disabled, but the GET-call from the dataadapter allways includes following parameters in the GET-url:
?filterscount=0&groupscount=0&pagenum=0&pagesize=10&recordstartindex=0&recordendindex=18&_=1386768031615
I want to get all data, then cache it clientside for paging and filtering, but in the first step i just want to get my data bound to the grid.
Here’s my code:
var source = {
type: "GET",
datatype: "json",
datafields: [
{ name: 'url' },
{ name: 'category', type: 'int' },
{ name: 'info' },
{ name: 'status', type: 'bool' }
],
url: '/api/redirects/Getallredirects',
id: 'id'
};
var dataAdapter = new $.jqx.dataAdapter(source, {
contentType: 'application/json; charset=utf-8',
loadError: function (xhr, status, error) {
alert(error);
},
downloadComplete: function (data) {
var returnData = {};
returnData.records = data.d;
return returnData;
}
});
$("#jqxgrid").jqxGrid({
source: dataAdapter,
filterable: false,
pageable: false,
virtualmode: false,
columns: [
{ text: 'URL', dataField: 'url', width: 100 },
{ text: 'Category', dataField: 'category', width: 100 },
{ text: 'Info', dataField: 'info', width: 180 },
{ text: 'Status', dataField: 'status', width: 80, cellsalign: 'right' },
]
});
I don’t get any data, the GET-call fails because of the automatically included parameters. How do i get rid of these parameters?
I just found in the jqxGrid documentation a reference to these parameters, but no example, how to remove them:
http://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxgrid/jquery-grid-extra-http-variables.htm
Thanks in advance for any help.
The below will remove the default parameters:
var dataAdapter = new $.jqx.dataAdapter(source,
{
formatData: function (data) {
return {};
}
}
);

Kendo.Web Grid Popup Create with ComboBox

I am using the free Kendo web controls. I have used the grid view in several places before and decided to use the popup style editing for my current project.
I have most of it working. I have three combo boxes for category, bank account and payee and when I edit an existing item, the model object passed back to my MVC action has the correct values in it. However, when I click on the create button, the three combo box values are returned as null to the controller.
Here is the CSHTML code for this view:
#using System
#using System.Linq
#{
ViewBag.Title = "Transactions";
}
#section Head
{
<link href="~/Content/kendo/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/kendo.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/kendo.web.min.js"> </script>
}
#section featured
{
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title</h1>
</hgroup>
</div>
</section>
}
<div id="grid"></div>
<script>
$(function() {
$("#grid").kendoGrid({
height: 350,
toolbar: [{ name: "create", text: "Create New Transaction" }],
columns:
[
{ field: "Date", width: "100px", template: '#= kendo.toString(Date,"MM/dd/yyyy") #' },
{ field: "Amount", format: "{0:c}", width: "100px" },
{ field: "Category", width: "80px", editor: categoryDropDownEditor, template: "#=Category.Name#" },
{ field: "BankAccount", title: "Account", width: "80px", editor: bankAccountDropDownEditor, template: "#=BankAccount.Name#" },
{ field: "Payee", width: "80px", editor: payeeDropDownEditor, template: "#=Payee.Name#" },
{ command: ["edit", "destroy"], title: " ", width: "160px" }
],
editable: { mode: "popup", confirmation: "Are you sure you want to delete this transaction?" },
pageable:
{
refresh: true,
pageSizes: true
},
sortable: true,
filterable: false,
dataSource:
{
serverPaging: true,
serverFiltering: true,
serverSorting: true,
pageSize: 7,
schema:
{
data: "Data",
total: "Total",
model:
{
id: "Id",
fields:
{
Id: { editable: false, nullable: true },
Date: { type: "Date" },
Amount: { type: "number", validation: { required: true, min: 0 } },
Category: { validation: { required: true } },
BankAccount: { validation: { required: true } },
Payee: { validation: { required: true } },
Note: { validation: { required: false } }
}
}
},
batch: false,
transport:
{
create:
{
url: "#Url.Action("Create", "Transaction")",
contentType: "application/json",
type: "POST"
},
read:
{
url: "#Url.Action("Read", "Transaction")",
contentType: "application/json",
type: "POST"
},
update:
{
url: "#Url.Action("Update", "Transaction")",
contentType: "application/json",
type: "POST"
},
destroy:
{
url: "#Url.Action("Delete", "Transaction")",
contentType: "application/json",
type: "POST"
},
parameterMap: function(data)
{
return JSON.stringify(data);
}
}
}
});
function categoryDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetCategories", "Transaction")" }
}
});
}
function bankAccountDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetBankAccounts", "Transaction")" }
}
});
}
function payeeDropDownEditor(container, options)
{
$('<input required data-text-field="Name" data-value-field="Id" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList(
{
autoBind: true,
dataValueFileld: "Id",
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});
}
});
</script>
The binding to the kendo combo box must be working, otherwise the edit would fail as well. All I can think is that the object is not created correctly. Also, it selects the first item in the combo box by default, but even so, does not bind the value.
Following is the code for my create and update actions:
[HttpPost]
public ActionResult Create(TransactionModel transactionModel)
{
var transaction = _moneyBO.CreateTransaction();
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
public ActionResult Update(TransactionModel transactionModel)
{
var transaction = _moneyBO.Transactions.SingleOrDefault(x => x.Id == transactionModel.Id);
if (transaction == null)
return View("NotFound");
Mapper.Map(transactionModel, transaction);
_moneyBO.UpdateTransaction(transaction);
return Json(Mapper.Map<TransactionModel>(transaction));
}
I have not found a good example using the popup custom edit. The example on the Kendo site works inline, but if you change the example to popup it does not work.
I have a same problem. Write, if you solve it, please
I found, that Kendo think that "null" (default for int?) is ObservableObject (while initialization of ComboBox), thats why it can't be parsed to "number". If you edit item (not create), value id not "null" and model bindind work's fine
Not sure if it's the only issue here but in your code example it looks like the initialization of your dropdown isn't quite correct. You have written dataValueFileld which should be dataValueField
kendoDropDownList({
autoBind: true,
dataValueFileld: "Id", <-- Incorrect spelling
dataTextField: "Name",
dataSource:
{
type: "json",
transport: { read: "#Url.Action("GetPayees", "Transaction")" }
}
});

Resources