Kendo ColorPalette not posting value to controller - javascript

I'm currently trying to get a kendo ColorPalette to work with inline editing on my grid. I've pretty much got it all figured out except that I'm having some difficulties posting the selected color value to my controller.
Kendo Grid:
$("#ContactTagsGrid").kendoGrid({
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Admin/Tag/GetTagsByOrg",
dataType: "json",
data: {
orgId: OrganizationId
}
},
create: {
url: "/Admin/Tag/Create",
dataType: "json",
type: "POST",
data: function () {
return kendo.antiForgeryTokens();
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number", nullable: true },
OrgId: { type: "number" },
Name: { type: "string" },
Color: { type: "string", defaultValue: "#f20000", validation: { required: true } }
}
}
},
pageSize: 20
}),
pageable: true,
sortable: true,
filterable: {
extra: false
},
scrollable: false,
columns: [
{
field: "Id",
hidden: true
},
{
field: "Name"
},
{
field: "Color",
editor: colorEditor,
template: function(dataItem) {
return "<div style='width: 25px; background-color: " + dataItem.Color + ";'> </div>";
},
width: "500px"
},
{
command: [
{
name: "Edit",
template:
"<a href='\\#' class='small btn btn-link k-grid-edit edit-text'><span class='fa fa-pencil'></span>Edit</a>",
text: "",
className: "fa fa-pencil"
},
{
template:
"<a href='\\#' class='small btn btn-link danger delete-text k-grid-delete'><span class='fa fa-trash-o'></span>Delete</a>",
name: "Delete",
text: " Delete",
className: "fa fa-trash-o"
}
],
width: "170px"
}
],
editable: {
mode: "inline",
destroy: false // don't use the kendo destroy method since we're using bootbox
},
// Custom save/cancel buttons
edit: function (e) {
var command = e.container.find("td:last");
command.html("<a href='\\#' class='small btn btn-primary k-grid-update'>Save</a><a href='\\#' class='small btn btn-default k-grid-cancel' style='margin-left: 5px'>Cancel</a");
}
});
Javascript to replace the default grid inline-editor with the Kendo ColorPalette:
function colorEditor(container, options) {
// create an input element
var div = $("<div></div>");
var input = $("<input />");
input.attr("name", "Color");
// append it to the container
div.appendTo(container);
input.appendTo(div);
// initialize a Kendo UI ColorPicker
div.kendoColorPalette({
palette: [
"#f20000", "#c60000", "#337a00"
],
columns: 3,
change: function () {
var color = this.value();
$("input[name=Color]").val(color);
}
});
}
When I click on the Save button, the only values that are posted to my controller are the Name and the OrgId.
If I set a defaultValue in the schema of my model like I did in the code above, then the default value for Color is always posted no matter if I select a different color or not.
If I do not set a defaultValue in the schema, then the value that is posted for Color is null.
So basically, I just need help updating my model so that it is correct when posting to the controller. I can see that the value of my input <input name="Color" /> is being updated correctly every time that I select a new color but again, it's not actually posting the value that it contains.
Not sure if this is needed, but here is what my model looks like:
public class TagCreateViewModel
{
public int OrgId { get; set; }
public string Name { get; set; }
public string Color { get; set; }
}

I ended up stumbling across this question on SO that helped me solve my problem. I just adapted it to use the Kendo Color Palette instead and it works perfectly now.
function colorEditor(container, options) {
$("<div type='color' data-bind='value:" + options.field + "'/>")
.appendTo(container)
.kendoColorPalette({
palette: [
"#f20000", "#c60000", "#337a00", "#54b010", "#9adc0d", "#28cb9b", "#0eac98", "#0ed6e8", "#14a7d1",
"#bc0aef", "#560ea7", "#2713bc", "#1457d1"
],
columns: 7
});
}

Related

jQuery kendo grid popup editor doesn't pass dropdown values to .net MVC controller?

I am trying to edit a row in jquery kendo grid popup editor. But when I click on update button it does not submit selected dropdown values to the controller while it submits the other properties without any issues. I have tried many examples but nothing works well.
This is my code
var element = $("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: '/controller/GetEmployees',
update: {
url: "/controller/UpdateEmployee",
dataType: "json"
},
},
pageSize: 10,
serverPaging: true,
serverSorting: false,
schema: {
model: {
id: "EmployeeID",
fields: {
EmployeeID: { type: "number", editable: false },
EmployeeName: { type: "string", editable: true },
EmployeeStatus: { defaultValue: { ID: 1, Name: "Active" }, editable: true }
}
}
}
},
height: 500,
sortable: false,
pageable: false,
editable: "popup",
toolbar: ["create"],
columns: [
{
field: "EmployeeName",
title: "Employee Name",
width: "110px"
},
{
field: "EmployeeStatus",
title: "Status",
width: "110px",
editor: activeInactiveDropDownEditor,
template: "#=EmployeeStatus.Name#"
},
{
command: "edit",
width: "80px"
}
]
});
});
}
function activeInactiveDropDownEditor(container, options) {
$('<input required name="' + options.field + '" data-bind="ID"/>')
.appendTo(container)
.kendoDropDownList({
//autoBind: true,
dataTextField: "Name",
dataValueField: "ID",
dataSource: {
type: "json",
transport: {
read: "/controller/GetStatusList"
}
}
});
}
could anyone found the fault here please ?
Finally I found a solution. I just modified update request with a type property and it works well now.
update: {
type: 'post', // just added this and works well
url: "/controller/UpdateEmployee",
dataType: "json"
},
I think your problem is with the binding, I mean, it is not just add a data attribute bind with the field name, sometimes binding models to widgets needs some level of complexity. As I can't reproduce your whole snippet, I would suggest you to use options.model to set the input value, hence the widget can initialize with the right value:
function activeInactiveDropDownEditor(container, options) {
$('<input required name="' + options.field + '" value="' + options.model.ID + '" />')
If that doesn't works, set the value init parameter or anything like that.

Kendo grid generate dynamic html in a column based on column value?

I'm using kendo grid,where i have a requirement to generate dynamic HTML based on value of a column which will be returned by another function.I have the following code
$("#divGenerateLogin_kendogrid").kendoGrid({
dataSource: {
data: data,
pageSize: 10
},
sortable: true,
reorderable: true,
pageable: {
pageSizes: true,
buttonCount: 5
},
filterable: true,
// selectable: true ,
// dataBound: onDataBound,
columns: [
{
field: "StudentName",
title: "Student Name",
type: "string"
},
{
field: "Class",
title: "Class",
type: "string"
},
{
title: "Login",
template: "#: LoginColHtml(IsLoginAvilable==1) #"
}
]
});
function LoginColHtml(isLoginAvilable) {
var html = "";
if (isLoginAvilable == true) {
html = "<button type='button' class='btn-ressetpwd'><i class='fa fa-key'></i> reset password</button>";
} else {
html = "<button type='button' class='btn-generatelogin'><i class='fa fa-user'></i> generate login</button>";
}
// "<div>#: (IsGuardianLoginAvilable==1) #</div>";
return html;
}
Instead of returning actual html in a column its returning as a string. How can i add actual HTML to the column instead of as a string ?
FYI
I have tried with this and it worked
{
title: "Guardian Login",
template: "#= LoginColHtml(IsLoginAvilable==1) #"
}

Lazy Load with Scrollable {Virtual:true} not working in Kendo UI Grid

I am facing an issue to implement lazy loading in kendo ui grid.
I added scrollable virtual property and backend server side code to handle it but issues is after adding scrollable property I am unable to see scroll bar in my Grid.
Even the selected rows (20 page size) disappears off the bottom of the grid into the hidden overflow area.
Here is my code.
var managecustomerGrid = $("#customerGrid").kendoGrid({
dataSource: {
schema: {
data: "results",
total : "totalRecords",
model: {
id: "SRNUMBER",
fields: {
SRNUMBER : {type: 'number'},
CUSTOMERNAME : {type: 'string'},
DATEPAID : {type: 'string'}
}
}
},
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 20,
batch: false,
transport: {
read: {
type: "POST",
url: "/customer/customer.cfc",
dataType: "json",
error: function (xhr, error) {
alert('Error In Getting Customer Information.');
}
},
parameterMap: function(options, type) {
return {
ntPageNumber: options.page,
ntRowLimit: options.pageSize,
vcSortOrder: JSON.stringify(options.sort),
vcFilterCondition: JSON.stringify(options.filter)
}
}
}
},
toolbar: kendo.template($("#template").html()),
height: 600,
scrollable: {
virtual: true
},
filterable: {
operators: {
string: {
contains: "Contains",
startswith: "Starts with",
endswith: "Ends with",
eq: "Is equal to",
doesnotcontain: "Doesn't contain"
}
}
},
sortable: true,
columns: [
{ field: "SRNUMBER", title: "SR No.", width: "80px", template: "<span id='#=SRNUMBER#'>#=SRNUMBER#</span>"},
{ field: "CUSTOMERNAME", title: "Customer Name", width: "110px"},
{ field: "DATEPAID", title: "Date", width: "110px"},
{ command: ["edit","detail","cancel"], title: " ", title: "Actions", width: "130px", filterable: false, sortable: false}
]
});
Please let me know if any one find any issues. I am unable to get it.
The kendo grid does not really support Lazy Loading out of the box. It may be easier to instead just make a blank scroll-able grid (without paging), and then to populate the data with ajax calls. You can use $.merge() to append data to the data array with little to no impact on performance.
$.ajax({
url: '/getNextData',
data: { filter: 'foo', lastLoaded: $("#Grid").data("kendoGrid").dataSource.at($("#Grid").data("kendoGrid").dataSource.total()-1).ID },
dataType: "json",
success: function (newData) {
$("#Grid").data("kendoGrid").dataSource.data($.merge($("#Grid").data("kendoGrid").dataSource.data(), newData))
},
error: function (e) { console.log(e); }
});
In this ajax example I load the next data based on the current last item in the grid and a filter. I just append the response to the currently loaded data.
I faced the same issue, my problem was the controller code. Here I am posting my controller hoping it would help someone someday
public JsonResult GetJson(int? projectid,int skip, int take, int pageSize, int page)
{
using (sqlCon)
{
var myData = sqlCon.Query<Device>("Select * from workbook.dbo.TargetList", new { projectid = projectid });
var data = myData .Skip(skip).Take(pageSize).ToList();
var total = myData .Count();
var json = new { data = myData };
var jsonResult = Json(new {data= data, total= total}, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
}

how to go to new line in kendo grid with enter key press

here i have developed a web application in mvc4 razor using some kendo ui widgets.in my appication there is a kendo grid which has used to view, update and insert records.
when i press the "add new record" button in grid, inserting a new record will available and with the press of "enter key" i can go to next cell(next column) of the current row.
it will help to insert data in each cell and go to next cell just pressing enter key without clicking each column(with the low number of mouse clicks).
but my next challenge is i need to go to next row(a new record) when i press the enter key at the last cell(last column) of the current row.
here is the code of grid and script i'm using.
<button class="k-button" id="batchGrid">
Batch Edit</button>
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script>
$("#batchGrid").click(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true} },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} }
}
}
}
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: true,
pageable: true,
height: 430,
width: 300,
toolbar: ["create", "save", "cancel"],
columns: [
{ field: "ProductID", title: "No", width: "90px" },
{ field: "ProductName", title: "Product Name" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "130px" },
{ command: ["destroy"], title: " ", width: "175px" }
// { field: "", title: "No", template: "#= ++record #", width: "30px" },
],
editable: { mode: "incell", createAt: "bottom" }
});
});
</script>
<script type="text/javascript">
function onDataBound(e) {
$("#batchgrid").on("focus", "td", function (e) {
var rowIndex = $(this).parent().index();
var cellIndex = $(this).index();
$("input").on("keydown", function (event) {
if (event.keyCode == 13) {
$("#batchgrid")
.data("kendoGrid")
.editCell($(".k-grid-content")
.find("table").find("tbody")
.find("tr:eq(" + rowIndex + ")")
.find("td:eq(" + cellIndex + ")")
.next()
.focusin($("#batchgrid")
.data("kendoGrid")
.closeCell($(".k-grid-content")
.find("table")
.find("tbody")
.find("tr:eq(" + rowIndex + ")")
.find("td:eq(" + cellIndex + ")")
.parent())));
return false;
}
});
});
}
</script>
but the problem is when i press the enter key at the last cell of any row it will not give me a new record(new line).
please help me here..
I'm having same issue, I was able to create new row with enter key press, but the problem is on the page, when ever I press enter key, its creating a new row in the grid, which is not desired. I need to filter the event say for example when the grid is in focus. but I'm not being able to do that yet. Here is my code:
$(document.body).keypress(function (e) {
if (e.keyCode == 13) {
var grid = $("#grid").data("kendoGrid");
grid.addRow();
}
});
If you can set the filter, it will work fine. Let me know if you can sort it out. Thanks.

add record function in Kendo UI grid is called many times

I am using this html code for Keno UI grid
function loadPhoneGrid(salesRepsId){
$("#phone-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_phones_sales_reps.php?salesRepsId="+salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_phone_number.php?salesRepsId="+salesRepsId,
type: "POST"
},
destroy: {
url: "operations/delete_phone.php",
type: "POST"
},
create: {
url: "operations/add_phone.php?salesRepsId="+salesRepsId,
type: "POST",
},
},
schema: {
data:"data",
total: "data.length", //total amount of records
model: {
id: "PhoneId",
fields: {
PhoneType: { defaultValue: { PhoneTypeId: 1, PhoneTypeName: "Work"} },
PhoneNumber: { type: "string" },
IsMainPhone: {type: "boolean", editalbe:true},
}
}
},
pageSize: 5,
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [
{
field:"PhoneType",
title:"Type",
editor: PhoneTypeDropDownEditor,
template: "#=PhoneType.PhoneTypeName#"
},
{
field: "PhoneNumber",
title:"Phone Number",
},
{
field: "IsMainPhone",
title:"Is Main",
width: 65,
template: function (e){
if(e.IsMainPhone== true){
return '<img align="center" src ="images/check-icon.png" />';
}else{
return '';
}
}
// hidden: true
},
{ command: "destroy", title: " ", width: 90 },
],
});
}
The code in the server side is (add_phone.php)
<?php
require_once("../lib/Phone.php");
$phone = array();
foreach($_POST as $name => $value){
$phone[$name] = $value;
}
Phone::AddPhoneNumber($_GET["salesRepsId"], $phone);
?>
For the first time, I added a new record. add_phone.php is calling once and everything is working fine. For the second time (with out refresh the page) when I try to add a new record, add_phone.php is called twice. One of them contains the first record which has been added to database before and the second is the new the data.
in the result I have 3 records ( 2 same data of first insert) and one new.
This an example to make it clear ( inspect the post request with firebug)
first click on save button (false, (111) 111-1111, 4,Fax) // after I enter this phone (111) 111-1111
second click on save button (false, (111) 111-1111, 4,Fax) in addition to (false, (222) 222-2222, 3,Work) // after I added this (222) 222-2222
Any help ??
May be your ajax request raise an error. You can see it by subscribing to the error event of your datasource.
In case of error, the data are not synchronized in your datasource. In your case, I think your dataitem stay in "dirty mode" so the datasource try to insert them for each synchronization...

Categories

Resources