Kendo UI Grid with form in popup - kendo-ui

I want to implement individual form for ajax call. I want to have a command, which opens new popup window with one field, user fills this field and then clicks "Send" and then I do an ajax call to controller. My code:
$(document).ready(function () {
var grid = $("#memberList-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("MemberSearchList", "RandomPoolSelection"))",
type: "POST",
dataType: "json",
data: function () {
var data = {
SearchMember: $('##Html.IdFor(model => model.SearchMember)').val(),
SelectionId: $('#SelectionId').val()
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
pageSize: #(Model.PageSize),
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
pageSizes: [#(Model.AvailablePageSizes)],
#await Html.PartialAsync("_GridPagerMessages")
},
scrollable: false,
columns: [
{
field: "PrimaryID",
title: "#T("PoolMemberList.Fields.PrimaryID")",
width: 150
},
{
field: "FirstName",
title: "#T("PoolMemberList.Fields.FirstName")",
width: 150
},
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
]
});
wndExclude = $("#exclude")
.kendoWindow({
title: "Excuse Reason",
modal: true,
visible: false,
resizable: false,
width: 300
}).data("kendoWindow");
excludeTemplate = kendo.template($("#excludeTemplate").html());
});
function showExclude(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
wndExclude.content(excludeTemplate(dataItem));
wndExclude.center().open();
}
and template :
<script type="text/x-kendo-template" id="excludeTemplate">
<div id="exclude-container">
<input type="text" class="k-input k-textbox" id="note">
<br />
</div>
</script>
how to implement sending this data (with ID) to controller?

A simple way to do what you want is using a partial view.
this is your command grid
{
command:
{
text: "Exclude",
click: showExclude
},
title: " ",
width: 100
}
and here your function :
function showExclude(e) {
$(document.body).append('<div id="excludeWindow" class="k-rtl"></div>');
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$('#excludeWindow').kendoWindow({
width: "80%",
title: 'excludeForm',
modal: true,
resizable: false,
content: "/YourController/GetPartial?id=" + dataItem.Id,
actions: [
"Close"
],
refresh: function () {
$("#excludeWindow").data('kendoWindow').center();
},
close: function() {
setTimeout(function () {
$('#excludeWindow').kendoWindow('destroy');
}, 200);
}
}).data('kendoWindow');
}
After clicking on the button, you load your window(popup) and call an action that loads a partial view to fill the content of the window.
You can pass whatever you want to your partial view (for example, here I just send Id)
public ActionResult GetPartial(Guid id)
{
var viewModel= new ViewModelExclude
{
Id = id,
};
return PartialView("_exclude", viewModel);
}
and the partial view is something like this:
#model ViewModelExclude
#using (Html.BeginForm("", "Your action", FormMethod.Post, new { id = "SendForm"}))
{
<input class="k-rtl" name="#nameof(Model.Id)" value="#Model.Id">
<button type="submit" class="btn btn-primary">Send</button>
}
and then call Your ajax after clicking on send button:
$("#SendForm").submit(function (e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
type: "POST",
url: '#Url.Action("send", "yourController"),
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function (data) {
}
});
});
Your send action something like this:
[HttpPost]
public ActionResult Send(ViewModelExclude view)
{
....
return Json();
}

Related

kendo tooltip is shown only after second 'hover' event

I use kendo grid and want to show kendo tooltip for icon in header cells.
I have the following code:
<div id="grid"></div>
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("List", "i3screenResult"))",
type: "POST",
dataType: "json",
data: function () {
var data = {
};
addAntiForgeryToken(data);
return data;
}
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors"
},
},
dataBinding: function (e) {
$('.questionmark').on("hover", function () {
var tooltip = $(this).kendoTooltip({
content: $(this).attr('tooltip'),
width: 120,
position: "top",
animation: {
open: {
effects: "zoom",
duration: 150
}
}
}).data("kendoTooltip");
});
},
scrollable: false,
columns: [
{
field: "BackgroundReportAccount",
headerTemplate: "#T("DrugConsortium.i3screen.Fields.BackgroundReportAccount") <img src='/images/question-mark-icon.png' class='questionmark' tooltip='#T("DrugConsortium.i3screen.Fields.BackgroundReportAccount.Details")' />",
width: 150
},
{
field: "ProviderReferenceId",
headerTemplate: "#T("DrugConsortium.i3screen.Fields.ProviderReferenceId") <img src='/images/question-mark-icon.png' class='questionmark' tooltip='#T("DrugConsortium.i3screen.Fields.ProviderReferenceId.Details")' />",
width: 150
},
//....
]
});
});
</script>
It works, but only since second hover event for img.
Why so and how to fix?
Try this AFTER grid initialization:
$('#grid').kendoTooltip({
content: function(e) {
return $(e.target).attr('tooltip');
},
filter: 'img.questionmark',
width: 120,
position: "top",
animation: {
open: {
effects: "zoom",
duration: 150
}
}
});
Also, you should change the attribute name from tooltip to data-tooltip since tooltip is not a standard HTML attribute. Then you can get it's value with $(e.target).data('tooltip');
Demo

How I write a dynamic URL in kendo UI DataSource like "update/{id}"

I have a web API. In that I wrote a update method. But it need to id of the table row to update to the row.
I use a grid to show data and use a toolbar to edit the row.
My question is how I pass that id to the update.
Can someone guide me ??
update: function(options) {
$.ajax( {
url: function(data) { return "updateUsuarios/"+data.Id,
dataType: "json",
.....
Well i suggest you, explain more your question, but i think this examples could help , if you have a toolbar as a template like this:
<script type="text/x-kendo-template" id="template">
<div class="toolbar">
<button type="button" id="update">Update</button>
</div>
</script>
You "grid" need the attr "toolbar"
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 550,
filterable:true,
toolbar: kendo.template($("#template").html()),
columns: [
{ field:"username", title: "Username" , width: "120px" },
{ field: "nombre", title:"Nombre", width: "120px" },
{ field: "apellido", title:"Apellido", width: "120px" },
{ field: "ci", title:"Documento de Identidad", width: "120px" },
{ field: "email", title:"Direccion de Correo", width: "120px" },
{ field: "activo",title:"Estatus", width: "120px" },
{ field: "fecha_caducidad",title:"Fin Demo", width: "120px",template: "#= kendo.toString(kendo.parseDate(fecha_caducidad, 'yyyy-MM-dd'), 'MM/dd/yyyy') #" },
{ field: "licencia_status",title:" ", width: "40px",template:'<img src="assets/images/#:data.licencia_status#.png"/>' },
{ command: ["edit"], title: " ", width: "120px" }],
editable: "popup",
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
selectable: true
});
So,you can configure a kendo button and add functionality in the event click:
$("#update").kendoButton({
click: function(){
//Here you will have the selected row
var self=$('#grid').data('kendoGrid')
var index = self.items().index(self.select());
var rowActual= self.dataSource.data()[index];
rowActual=self.dataItem(self.select());
if(rowActual==undefined || rowActual ==null) {
alert("No row selected");
}else{
$.ajax({
type: "POST",
url: "update",
data: {
id:rowActual.id
},
dataType: 'json',
success: function (data) {
},
error: function(){
}
});
}
}
});
and send in the ajax the row id, but if you are update the row with the inline edition you could try with a datasource like this
dataSource = new kendo.data.DataSource({
transport: {
read: function(options) {
$.ajax( {
url: "readUsuarios",
dataType: "json",
success: function(result) {
options.success(result);
}
});
},
update: function(options) {
$.ajax( {
url: "updateUsuarios",
dataType: "json",
data: {
models: kendo.stringify(options.data.models)
},
success: function(data) {
// response server;
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "id",
fields: {
username: { editable: false, nullable: true },
nombre: { validation: { required: true } },
apellido: { type: "string", validation: { required: true} },
ci: { type: "string", validation: { required: true} },
email: { type: "string", validation: { required: true } },
activo: { type: "boolean",editable: false },
fecha_caducidad: { type: "date" },
licencia_status:{editable: false}
}
}
}
});
I hope this help!

Update in kendo grid in mobile app does not send model

I am trying to update a row from a grid in a mobile app , but the model is not sent to the server.
I am using kendo 2015.1.429
My view is this:
<div data-role="view" data-init="initGrid" data-stretch="true">
<div data-role="header">
</div>
<div id="grid">
</div>
</div>
<script type="text/javascript">
function initGrid() {
var dataSource3 = new kendo.data.DataSource({
transport: {
read: {
url: "#Url.Action("GetAll")",
dataType: "json"
},
update: {
url: "#Url.Action("Update")",
dataType: "json"
},
destroy: {
url: "#Url.Action("Destroy")",
dataType: "json"
},
create: {
url: "#Url.Action("Create")",
dataType: "json"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: false,
schema: {
data:"Data",
model: {
id: "ID",
fields: {
ID: { type: "number", editable: false, nullable: false },
Name: { type: "string" }
}
}
}
});
$("#grid").kendoGrid({
dataSource:dataSource3,
pageable: true,
mobile: "tablet",
height: kendo.support.mobileOS.wp ? "24em" : 430,
resizable: true,
editable: {
mode: "popup"
},
toolbar: ["create"],
columns: [
{ field: "ID", title: "ID", width: 200},
{ field: "Name", title: "Name"},
{ command: ["edit", "destroy"] }
]
});
}
</script>
The Update method in controller is this:
public ActionResult Update([DataSourceRequest] DataSourceRequest request, Model viewModel)
{
return Json(new[] { viewModel }.ToDataSourceResult(request, ModelState));
}
<--EDITED 2 -->
I saw in Fiddler that no data is sent to my method Update.
What am I forgetting to do? What am I doing wrong?
If I remove parameterMap
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
It works fantastic.
Thanks!

Kendo UI Grid Toolbox Commands (Create, Save, Update) To enable Conditionally

I have a simple Kendo UI Grid. The gird is in batch mode and works fine. I am using Web API to bind the actual CRUD methods.
I have to show hide the Toolbar Buttons conditionally. How and Where (which event) can I create this kind of functionality
For example:
If(user.Role.Permission == "Edit"){
//Show Edit Button else hide
}
Here is the Actual Kendo UI Grid Code
var baseUrl = "/api/TicketType";
var datatype = "json";
var contentType = "application/json";
var datasource = new kendo.data.DataSource({
serverPaging: true,
pageSize: 10,
autoSync: false,
batch: true,
transport: {
read: {
url: baseUrl,
dataType: datatype,
contentType: contentType
},
create: {
url: baseUrl,
dataType: datatype,
contentType: contentType,
type: "POST"
},
update: {
url: baseUrl,
dataType: datatype,
contentType: contentType,
type: "PUT"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data.models) {
return kendo.stringify(data.models);
}
else {
return {
take: data.take,
skip: data.skip,
pageSize: data.pageSize,
page: data.page
}
}
}
},
schema: {
data: "data.$values",
total: "recordCount",
model: {
id: "TypeID",
fields: {
TypeID: { editable: false, type: "number" },
TypeCode: { editable: true, nullable: false, validation: { required: true } },
Description: { editable: true, nullable: false, validation: { required: true } }
}
}
}
});
$("#Grid").kendoGrid({
dataSource: datasource,
toolbar: [
{name: "create", text: "Add New Record"},
{ name: "save", text: "Save Changes" },
{ name: "cancel", text: "Cancel Changes" },
],
columns:
[
{ field: "TypeID", width: 50, title: "ID"},
{ field: "TypeCode", width: 150, title: "Code"},
{ field: "TypeDescription", width: 200, title: "Description"}
]
})
datasource.read(); // This will bind to the grid.
});
Please try with the below code snippet.
$(document).ready(function () {
hidetoolbar();
});
function onDataBound(arg) {
hidetoolbar();
}
function onDataBinding(arg) {
hidetoolbar();
}
function hidetoolbar(){
If(user.Role.Permission != "Edit"){
$("#Grid .k-add").parent().hide();
$("#Grid .k-update").parent().hide();
$("#Grid .k-cancel").parent().hide();
//OR
$("#Grid .k-add").parent().remove();
$("#Grid .k-update").parent().remove();
$("#Grid .k-cancel").parent().remove();
}
}
$("#Grid").kendoGrid({
dataSource: datasource,
dataBound: onDataBound, // Added
dataBinding: onDataBinding, //Added
toolbar: [
{name: "create", text: "Add New Record"},
{ name: "save", text: "Save Changes" },
{ name: "cancel", text: "Cancel Changes" },
],
columns:
[
{ field: "TypeID", width: 50, title: "ID"},
{ field: "TypeCode", width: 150, title: "Code"},
{ field: "TypeDescription", width: 200, title: "Description"}
]
});
If you want to show or hide the toolbar button, you will need to implement the logic in the Databound event of the Grid.
Please see the below example:
JSBin Databound example
Note: Your question is a duplicate of Make Command Button invisible in Kendo Grid.

Kendo UI toolbar buttons

I am using a Kendo UI grid, which looks like this:
function refreshGrid()
{
$(".k-pager-refresh.k-link").click();
}
var editWindow;
var fields= {FullName: {type: "string"}, Email: {type: "string"}, LogCreateDate: {type: "date"}};
var gridColumns =
[{
width: 90,
command: {
name: "edit",
text: "Edit",
click: function(e) {
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
editWindow = $("#edit").kendoWindow({
title: "Edit User",
modal: true,
visible: false,
resizable: false,
width: 800,
height: 400,
content: 'myediturl' + dataItem.ID
});
editWindow.data("kendoWindow").center().open();
return false;
}
}
},
{
width: 90,
command: {
name: "delete",
text: "Delete",
click: function(e) {
//alert(this.dataItem($(e.currentTarget).closest("tr")).ID);
var id = this.dataItem($(e.currentTarget).closest("tr")).ID;
if (confirm("Are you sure you want to delete this user?"))
{
$.ajax({
type: 'POST',
url: '#Url.Action("deleteuser","admin",null, "http")' + "/" + this.dataItem($(e.currentTarget).closest("tr")).ID,
success: function (param) { refreshGrid(); },
async: false
});
}
return false;
}
}
},
{
field: "FullName",
title: "Full Name",
type: "string"
},
{
field: "Email",
title: "Email",
type: "string"
},
{
field: "LogCreateDate",
title: "Created",
type: "date",
template: '#= kendo.toString(LogCreateDate,"MM/dd/yyyy") #'
}];
//getSorts the columns of the grid
function getColumns() {
//Parsing the set of columns into a more digestable form
var columns = "";
for (var col in gridColumns) {
if (!!gridColumns[col].field)
{
if (columns.length > 0) {
columns += ";";
}
columns += gridColumns[col].field + "," + gridColumns[col].type;
}
}
return columns;
}
function getSorts(sortObject) {
if (!(sortObject)) {
return "";
}
//Getting the row sort object
var arr = sortObject;
if ((arr) && (arr.length == 0)) {
return "";
}
//Parsing the sort object into a more digestable form
var columnSet = getColumns();
var returnValue = "";
for (var index in arr) {
var type = "";
for (var col in gridColumns) {
if (gridColumns[col].field === arr[index].field) {
type = gridColumns[col].type;
}
}
returnValue += ((returnValue.length > 0) ? (";") : ("")) + arr[index].field + "," + (arr[index].dir === "asc") + "," + type;
}
return returnValue;
}
var grid;
$(function () {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "mydatasourceurl",
type: "POST",
},
parameterMap: function (data, type) {
data.filters = JSON.stringify(data.filter);
data.columns = JSON.stringify(getColumns());
data.sorts = JSON.stringify(getSorts(data.sort));
console.log(data);
return data;
}
},
schema: {
fields: fields,
data: "Data",
total: "Total"
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
toolbar: [{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}],
height: 392,
groupable: false,
sortable: true,
filterable: true,
pageable: {
refresh: true,
pageSizes: true
},
columns: gridColumns
});
grid = $("#grid").data("kendoGrid");
});
My create toolbar action is not triggered on click. How can I resolve this problem, is Kendo UI able to handle toolbar click events? The best solution I came up with looks like this:
$(".k-button.k-button-icontext.k-grid-add").click(function () {
//If the window doesn't exist yet, we create and initialize it
if (!grids[gridContainerID].addWindow.data("kendoWindow")) {
grids[gridContainerID].addWindow.kendoWindow({
title: "Add " + entityName,
width: "60%",
height: "60%",
close: onClose,
open: onAddOpen,
content: addUrl
});
}
//Otherwise we just open it
else {
grids[gridContainerID].addWindow.data("kendoWindow").open();
}
//Centralizing and refreshing to prepare the layout
grids[gridContainerID].addWindow.data("kendoWindow").center();
grids[gridContainerID].addWindow.data("kendoWindow").refresh();
return false;
});
Thanks in advance.
Instead of using that complex selector use the one that Kendo UI creates from name:
toolbar: [
{
name: "Add",
text: "Add new record",
click: function(e){console.log("foo"); return false;}
}
],
and then:
$(".k-grid-Add", "#grid").bind("click", function (ev) {
// your code
alert("Hello");
});
In kendogrid docs here shows that there is no click configuration for grid toolbar buttons like grid.colums.commands.
To solve this problem you can reference following steps:
create a template for toolbar
<script id="grid_toolbar" type="text/x-kendo-template">
<button class="k-button" id="grid_toolbar_queryBtn">Query</button>
</script>
apply tempate to toolbar
toolbar:[{text:"",template: kendo.template($("#grid_toolbar").html())}]
add event listener to button
$("#grid_toolbar_queryBtn").click(function(e) {
console.log("[DEBUG MESSAGE] ", "query button clicked!");
});

Resources