Im updating the grid values from the database. And passing values from CS page to JSgrid. Delete,Edit is perfectly working with db. But after search the grid is not getting updated.I can pass the search value to the CS page and get the corresponding search value from DB. But the values are not getting updated with JSgrid.
var Status;
var lastPrevItem;
var clients =<%=gridData%>
$("#jsGrid").jsGrid({
width: "100%",
height: "450px",
filtering: true,
//filterable:true,
//inserting: true,
autosearch: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 25,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete the Department?",
controller: //db,
{ loadData: function (filter) {
if (filter["ID"] != "" || filter["Name"] != "") {
return $.ajax({
type: "POST",
async: true,
processdata: false,
paging: true,
contentType: "application/json; charset=utf-8",
url: "myurl/mycsmethod",
data: "{'ID':'" + filter["ID"] + "','Name':'" + filter["Name"]+ "'}",
success: function (data) {
},
error: function (XHR, errStatus, errorThrown) {
var err = JSON.parse(XHR.responseText);
errorMessage = err.Message;
alert(errorMessage);
}
});
}
},
updateItem: function (clients) {
var result = $.Deferred();
alert(result);
var ajaxDeferred = $.Deferred().reject();
alert(ajaxDeferred);
ajaxDeferred.done(function (updatedItem) {
result.resolve(updatedItem);
}).fail(function () {
result.resolve(lastPrevItem);
});
return result.promise();
},
},
onItemDeleting: function (args) {
//its working fine
},
onItemEditing: function (args) {
//its working fine
},
data: clients,
fields: [
{ type: "control" },
{ name: "ID", visible: false, width: 0, validate: "required" },
{ name: "Name", visible: false, width: 0, validate: "required" },
]
});
I want to update <%=gridData%> with jsgrid once the search button is triggered.
loadData: function(filter) {
return $.grep(clients, function(client) {
return (!filter["DeptID"] || client["DeptID"].indexOf(filter["DeptID"]) > -1)
&& (!filter["DeptName"] || client["DeptName"].indexOf(filter["DeptName"])>-1)
&& (!filter["Status"] || client["Status"].indexOf(filter["Status"]) > -1)
});},
updateItem: function (updatingClient) {
var result = $.Deferred();
alert(result);
var ajaxDeferred = $.Deferred().reject();
alert(ajaxDeferred);
ajaxDeferred.done(function (updatedItem) {
result.resolve(updatedItem);
}).fail(function () {
result.resolve(lastPrevItem);
});
return result.promise();
},
Its working now with the above code,friends.But If anything,i need to improve in my code, please let me know.
Related
I have Kendo Grid in my view. I have specified read , edit and delete each as of type HTTPPOST. But when I try to edit or delete i get an error that : "A public action method 'UpdateDetails' was not found on controller 'Nop.Plugin.Misc.CategoryWiseShipping.Controllers.ShippingChargeController'." for update Action and similarly one other for delete option.
Interesting thing is that it works fine on my local machine but throws error when published to server
I have searched extensivelly on google but couldn't find the reason as to why it is happening.
This is the controller actionMethod
[HttpPost]
public ActionResult UpdateDetails(ShippingChargeModel shippingChargeModel)
{
if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
return AccessDeniedView();
if (shippingChargeModel.SchoolEmail == null)
{
ErrorNotification(" Email can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleStartDate == null)
{
ErrorNotification(" Sale start date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate == null)
{
ErrorNotification(" Sale end date can not be null !!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
if (shippingChargeModel.SaleEndDate < shippingChargeModel.SaleStartDate)
{
ErrorNotification(" Sale start date should be less than sale end date!!", true);
return RedirectToAction("AddShippingCharge", "ShippingCharge");
}
var modelFromDb = _catShippingService.GetRecord(shippingChargeModel.Id);
modelFromDb.SaleEndDate = shippingChargeModel.SaleEndDate.Value.AddMinutes(330);
modelFromDb.SaleStartDate = shippingChargeModel.SaleStartDate.Value.AddMinutes(330);
modelFromDb.SchoolEmail = shippingChargeModel.SchoolEmail;
modelFromDb.ShippingCharge = shippingChargeModel.ShippingCharge;
modelFromDb.ModifyDate = DateTime.Now;
_catShippingService.Update(modelFromDb);
return new NullJsonResult();
}
This is my Kendo Grid :
function loadKendo() {
var dataNew = {};
$("#shippingCharge-grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: "#Html.Raw(Url.Action("GetDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
},
update: {
url: "#Html.Raw(Url.Action("UpdateDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
//data: addAntiForgeryToken
},
destroy: {
url: "#Html.Raw(Url.Action("DeleteDetails", "ShippingCharge"))",
type: "POST",
dataType: "json",
}
,
parameterMap: function (data, operation) {
if (operation === "update") {
dataNew.Id = data.Id;
dataNew.CategoryId = data.CategoryId;
dataNew.ShippingCharge = data.ShippingCharge;
dataNew.SaleStartDate = stringToTimestamp(data.SaleStartDate.toUTCString());
dataNew.SaleEndDate = stringToTimestamp(data.SaleEndDate.toUTCString());
dataNew.SchoolEmail = data.SchoolEmail;
return { ShippingChargeModel: dataNew };
}
return data;
}
},
schema: {
data: "Data",
total: "Total",
errors: "Errors",
model: {
id: "Id",
fields: {
//ProductId: { editable: false, type: "number" },
CategoryId: { editable: false, type: "string" },
CategoryName: { editable: false, type: "string" },
ShippingCharge: { editable: true, type: "number" },
SaleStartDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SaleEndDate: { editable: true, type: "date", format: "{0:dd/MMM/yyyy HH:mm}"},
SchoolEmail: { editable:true, type: "string" }
}
}
},
requestEnd: function (e) {
if (e.type == "update") {
this.read();
}
if (e.type == "cancel") {
this.cancelChanges();
}
},
error: function (e) {
display_kendoui_grid_error(e);
// Cancel the changes
this.cancelChanges();
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
pageable: {
refresh: true,
numeric: false,
previousNext: false,
info: false,
pageSizes: [#(gridPageSizes)]
},
editable: {
confirmation: "#T("Admin.Common.DeleteConfirmation")",
mode: "inline"
},
scrollable: false,
columns: [
{
field: "CategoryName",
title: "CategoryName",
width: 300
},
{
field: "ShippingCharge",
title: "Shipping Charge",
width: 100,
encoded: false
}
,
{
field: "SchoolEmail",
title: "Email",
width: 200,
encoded: false
}
,
{
field: "SaleStartDate",
title: "Sale Start Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleStartDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
},
{
field: "SaleEndDate",
title: "Sale End Date",
width: 200,
encoded: false,
type: "datetime",
format: "{0:dd/MMM/yyyy HH:mm}",
template: "#= kendo.toString(kendo.parseDate(SaleEndDate, 'yyyy-MM-dd'), 'dd/MMM/yyyy') #",
editor: dateTimeEditor
}, {
command: [
{
name: "edit",
text: {
edit: "#T("Admin.Common.Edit")",
update: "#T("Admin.Common.Update")",
cancel: "#T("Admin.Common.Cancel")"
}
}
, {
name: "destroy",
text: "#T("Admin.Common.Delete")"
}
],
width: 200
}
]
});
}
Please help me out. Any sort of insight will do ...
I have a kendo grid that is edited inline. One of the fields should be edited selecting an element from a list, but the list must have a hierarchical structure (would be nice be able of filter that list). I was thinking in use a kendo treeview as editor for that field but I haven't found any way to accomplish this. I tried make a custom editor template (using columns.Bound(s => s.FieldId).EditorTemplateName("_TreeEditorTemplate")) that render the treeview, but the treeview is not an input and is not selectable. I also thinked in make an editor that use a kendo dropdownlist with the tree inside but this is no currently supported by kendo. Any ideas???
Have you looked at the sample on the Kendo site: https://docs.telerik.com/kendo-ui/controls/data-management/grid/how-to/Editing/use-treeview-as-grid-editor
<div id="example">
<div id="grid"></div>
<script>
$(document).ready(function () {
var crudServiceBaseUrl = "//demos.telerik.com/kendo-ui/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 } },
Discontinued: { type: "boolean" },
UnitsInStock: { type: "number", validation: { min: 0, required: true } }
},
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
edit: function (e) {
//checking if a cell from the Test column is opened for editing
var dummyInput = e.container.find("input[name='test']");
if (dummyInput.length > 0) {
var treeView = $(e.container).find(".treeViewEditor").data("kendoTreeView");
var originalItem = treeView.findByText(dummyInput.val());
if (originalItem != null) {
// Select the item based on the field value
treeView.select(originalItem);
}
}
},
navigatable: true,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: [
"ProductName",
{
field: "test", title: "Test", width: 120,
editor: function (container, options) {
var input = $("<input class='tveInput'/>");
input.attr("name", options.field);
var tvDiv = $("<div class='treeViewEditor'></div>");
$(tvDiv).kendoTreeView({
animation: false,
dataSource: [
{
text: "foo1"
},
{
text: "foo2",
items: [
{ text: "bar" },
{ text: "bar1" },
{ text: "bar2" }
]
}
]
});
var treeView = $(tvDiv).data("kendoTreeView");
$(tvDiv).find(".k-in").mousedown(function (e) {
var clickedNode = $(e.toElement).closest("[role=treeitem]");
var dataItem = treeView.dataItem(clickedNode);
var dummyInput = clickedNode.closest("[role=gridcell]").find("input[name='test']");
dummyInput.val(dataItem.text);
dummyInput.trigger("change");
});
tvDiv.appendTo(container);
input.appendTo(container);
}
},
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: 120 },
{ field: "UnitsInStock", title: "Units In Stock", width: 120 },
{ field: "Discontinued", width: 120 },
{ command: "destroy", title: " ", width: 150 }],
editable: true
});
});
</script>
</div>
<style>
.tveInput {
display: none;
}
</style>
I have a jqgrid dropdownlist that is being populated with Json data from my database. It displays perfectly but when an option is clicked it does not take in the value selected and send it through. In other words it is just displaying in the drop down and nothing more. Here is my code for the colmodel field I am working with:
{
name: 'employee_speciality', index: 'employee_speciality', editable: true,
editrules: { required: true },
sortable: true,
align: 'center',
editable: true,
cellEdit: true,
edittype: 'select',
formatter:'select',
editoptions: {
dataUrl:"http://localhost:8080/service.svc/serviceBranch",
buildSelect: function (response) {
var data = typeof response === "string" ?
$.parseJSON(response) : response,
s = "<select>";
s += '<option selected="selected" style="display:none;">Choose here</option>';
$.each(data.serviceBranchResult, function () {
s += '<option value="' + this.service_name + '">' + this.service_name +
'</option>';
})
return s + "</select>";
}
}
}],
This is where I am retrieving the data, where employee_speciality is the only one with the dropdownlist:
function saveData() {
var rowid = $("#jqgrid").jqGrid('getGridParam', 'selrow');
var rowData = $("#jqgrid").getRowData(rowid);
var employee_name = rowData.employee_name;
var employee_surname = rowData.employee_surname;
var employee_username = rowData.employee_username;
var employee_email = rowData.employee_email;
var branch_id = rowData.branch_id;
var user_type = rowData.user_type;
var employee_state = rowData.employee_state;
var employee_speciality = rowData.employee_speciality;
alert(employee_speciality); //to check
var gridData = {
employee_name: employee_name,
employee_surname: employee_surname,
employee_username: employee_username,
employee_email: employee_email,
branch_id: branch_id,
user_type: user_type,
employee_state: employee_state,
employee_speciality: employee_speciality
};
gridData = JSON.stringify(gridData);
$.ajax({
type: "POST",
url: "Employees.aspx/save",
data: gridData,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response, textStatus, xhr) {
alert(employee_speciality);
location.reload(true);
},
error: function (xhr, textStatus, errorThrown) {
alert(employee_speciality);
Abort();
alert("Please enter all fields");
}
})
Please can I get some insight as to why this is happening, any help is highly appreciated. Thanks in advance
I have found a solution to my problem. Taking out the formatter: 'select' worked for me. Thanks for your time #David
i want to send data from kendo grid to sql database, here is my javascript view model code:
document.onreadystatechange = function () {
var viewModel = kendo.observable({
products: new kendo.data.DataSource({
schema: {
//data:"Data",
total: "Count",
model: {
Id: "Id",
fields: {
Id: { editable: true, type: "int" },
ShortName: { editable:true, type: "string" },
FullName: { editable: true, type: "string" },
ContactPerson: { editable: true, type: "string" },
CurrentCurrencyCode: { editable: true, type: "int" },
Adress1: { editable: true, type: "string" },
CompanyState: { editable: true, type: "string" },
CompanyCity: { editable: true, type: "string" },
CompanyCountry: { editable: true, type: "string" },
ZipPostCode: { editable: true, type: "string" },
TelArea: { editable: true, type: "string" }
}
}
},
batch: true,
transport: {
read: {
url: "/api/Companies/GetAllCompanies",
dataType: "json"
},
create:{
url: "/api/Companies/SaveDefCompny", // here is a correct api url, which i want to call
dataType: "json"
},
destroy: {
url: "/api/Companies/Delete",
dataType: "json"
},
parameterMap: function (data, operation) {
if (operation !== "read" && data) {
return kendo.stringify(data) ;
}
}
}
})
});
kendo.bind(document.getElementById("example"), viewModel);
}
Here is my controller code to post data to database but its is not calling by clicking create or update button what the problem with my grid or controller call?
[HttpPost]
public void SaveDefCompny(IEnumerable<DefCompanyDTO> DfCmpny1)
{
var result = new List<DefCompany>();
using (var data = new RPDBEntities())
{
foreach (var productViewModel in DfCmpny1)
{
var product = new DefCompany
{
Id = productViewModel.Id,
CurrentCurrencyCode = productViewModel.CurrentCurrencyCode,
ShortName= productViewModel.ShortName,
FullName= productViewModel.FullName,
ContactPerson= productViewModel.ContactPerson,
Address1= productViewModel.Address1,
CompanyCity= productViewModel.CompanyCity,
CompanyState= productViewModel.CompanyState,
CompanyCountry= productViewModel.CompanyCountry,
ZipPostCode= productViewModel.ZipPostCode,
TelArea= productViewModel.TelArea
};
result.Add(product);
data.DefCompanies.Add(product);
};
data.SaveChanges();
}
}
the url is correct but it doesnot called even while debugging cursor not goes to url but grid reads all values and display in it
As you are going to post data type: "POST" is missing in create method.
And also check posting data.models instead of data
hiii to all, i am using jqgrid, and want to display error message if the user wants to delete the truck record which is in use, i have to display a error message truck in use..
here is my jqgrid:-
jQuery(document).ready(function () {
var grid = jQuery("#TrucksGrid141");
grid.jqGrid({
url: '/Admin/GetTrucksForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/SaveTruck',
height: '100%',
pager: '#pagerTrucks',
colNames: ['Id', 'Name', ''],
colModel: [
{ name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Name', index: 'Name', align: "center", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Delete', index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }
],
width: '490',
caption: 'Company Trucks',
hidegrid: false,
delete: true,
cellEdit: true,
viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted != 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
//grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
}
}
}
}
);
grid.jqGrid('navGrid', '#pagerTrucks',
{ resize: false, add: false,search:false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pagerTrucks',
{ title: "Add New Truck", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewTruckModal, position: "First", caption: "" });
});
function showNewTruckModal() {
var grid = jQuery("#TrucksGrid141");
$("#formAddNewTruck").dialog(
{
open: function (event, ui) {
$("#txtName").val('');
$("#trFormErrorTrucks").hide();
$("#trFormErrorTrucks td").text('');
},
buttons: {
"Submit": function () {
debugger;
if (ValidateUsers() == true) {
$('#error').ajaxError(function (event, request, settings) {
$('#waiting').hide();
$(this).addClass('errordiv').text(request.statusText + "" + request.status);
});
$.post('/Admin/AddNewTruck/',
$('#formAddNewTruck').serialize(),
function (data) {
debugger;
if (data == 'Success') {
$('#formAddNewTruck').dialog("close");
grid.jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
else {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(data);
}
});
}
},
"Cancel": function () {
$('#error').removeClass("errordiv").text("");
$('#waiting').hide();
$(this).dialog("close");
}
},
modal: true,
title: "New Truck",
minWidth: 400,
resizable: false
}
).dialog('open');
}
function ValidateUsers() {
var flag = true;
var errorMSG = '';
$("#trFormErrorTrucks td").text('');
if ($("#txtName").val() == '') {
errorMSG += 'Truck Name cannot be blank';
flag = false;
}
if (flag == false) {
$("#trFormErrorTrucks").show();
$("#trFormErrorTrucks td").text(errorMSG);
}
else {
$("#trFormErrorTrucks td").text('');
$("#trFormErrorTrucks").hide();
}
return flag;
}
function deleteRow(rowid) {
jQuery("#TrucksGrid141").delGridRow(rowid, { url: '/Admin/TruckDelete', caption: 'Delete User?', msg: 'Delete selected User? <br />Careful, this is irreversable!', resize: false,success:abc });
}
function emptyText(rowid, cellname, value, iRow, iCol) {
if (cellname == 'Password')
return "";
}
function abc(data)
{
debugger;
}
and here is my cs code from controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TruckDelete(int Id)
{
var error = "";
bool result=true;
DataContext db = new DataContext();
Truck udelete= db.Trucks.Where(el => el.Id == Id).FirstOrDefault();
if (udelete != null)
{
JobSites_ForSnow snow = db.JobSites_ForSnow.Where(el => el.TruckId == Id).FirstOrDefault();
JobSite normal = db.JobSites.Where(el => el.TruckId == Id).FirstOrDefault();
if(snow==null && normal==null)
{
db.Trucks.Remove(udelete);
db.SaveChanges();
}
else
{
error = "Truck in use!";
result= false;
}
}
else
{
error = "Record Not Found!";
result= false;
}
return Json(result,error);
}
can anybody tell me how can i display the error message? i have seen this answer (jqgrid error message on delete) but didn't understood what to do :(. if the question is not clear to you, please let me know by comment, i will explain ...thanks in advance :)
You use currently
return Json(result,error);
as the last line of TruckDelete action, where result have boolean type and error is a string. So the Controller.Json Method (Object, String) where error will be interpreted as contentType of HTTP response. It's your first problem. You should use probably something like
return Json(new Object[] {result, error});
(see here). In the case the method will generate JSON response like
[true,""]
or
[false,"Record Not Found!"]
The client side (jqGrid) can process the response inside of afterSubmit callback. You need just replace unknown (for jqGrid) option success of delGridRow to the following
jQuery("#TrucksGrid141").delGridRow(rowid, {
url: '/Admin/TruckDelete',
caption: 'Delete User?',
msg: 'Delete selected User? <br />Careful, this is irreversable!',
resize: false,
afterSubmit: function (jqXHR) {
return $.parseJSON(jqXHR.responseText); // return decoded response
}
});