I'm developing a web based application using bootstrap.
I'm trying to implement inline editing in my grid on page load but i'm facing some issue while displaying the success or failure message after performing edit function.
Here is my code :
$(document).ready(function () {
var GetUrl = Web_Path + '/Test/TestHandler/GetTestData/' + AjaxHandlerName;
jQuery("#jqGrid-container").jqGrid({
url: GetUrl,
datatype: 'json',
mtype: 'POST',
postData: { SearchInfo: function () { return getSearchPostData() } },
colNames: [' ', 'ID', 'Name', 'ContactNo', 'EmpId', 'MailId', 'RoleName'],
colModel: [
{ name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,
formatter: 'actions',
formatoptions: {
keys: true,
delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
}
},
{ name: 'Id', index: 'Id', hidden: true, editable: true },
{ name: 'Name', index: 'Name', validation: { required: true }, sortable: true, editable: true, editoptions: { size: "40", maxlength: "50"} },
{ name: 'ContactNo', index: 'ContactNo', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
{ name: 'EmpId', index: 'EmpId', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
{ name: 'MailId', index: 'MailId', sortable: false, editable: true, editoptions: { size: "40", maxlength: "50"} },
{name: 'RoleName', index: 'RoleName', sortable: false }
],
editurl: ISM_Web_Path + '/Test/TestHandler/UpdateTestContacts/' + ISMAjaxHandlerName,
ajaxRowOptions: {
afterEditRow: function (rowid, cellname, value, iRow, iCol) {
alert('success');
}
},
serializeRowData: function (postdata) {
return { ContactInfo: JSON.stringify(postdata) };
},
jsonReader: {
id: 'Id',
repeatitems: false
},
height: "100%",
pager: '#jqGrid-pager',
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'Id',
sortorder: 'desc',
viewrecords: true,
caption: "JQ grid data",
loadComplete: function () {
var table = this;
updatePagerIcons(table);
}
});
});
function getSearchPostData() {
var searchData = {};
searchData.Id=1;
return JSON.stringify(searchData);
}
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
'ui-icon-seek-prev': 'icon-angle-left bigger-140',
'ui-icon-seek-next': 'icon-angle-right bigger-140',
'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
<div class="row">
<div class="col-xs-12">
<table id="jqGrid-container" class="ui-jqgrid ui-widget ui-widget-content ui-corner-all">
</table>
<div id="jqGrid-pager">
</div>
</div>
</div>
Handler function
public void UpdateTestContacts(HttpContext context)
{
TestContact contactInfo =new TestContact();
string jsonData = context.Request.Params["ContactInfo"];
MemoryStream TestContactMs = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TestContact));
contactInfo = (RelationshipContact)serializer.ReadObject(TestContactMs );
//call manger function
// return true or false
}
TestContact.cs
public class TestContact
{
public int Id { get; set; }
public string Name { get; set; }
public string ContactNo { get; set; }
public string EmpId { get; set; }
public int RelId { get; set; }
public int TypeId { get; set; }
public string MailId { get; set; }
public string RoleName { get; set; }
}
I have used jquery.jqGrid.min.js.
I'm unable to display success message after editing the row successfully.
I have used afterEditRow
Please help me out.
There are no afterEditRow callback function inside of ajaxRowOptions. I recommend you to use aftersavefunc callback function of inline editing which can be specified as afterSave function of formatoptions:
formatter: 'actions',
formatoptions: {
keys: true,
afterSave: function (rowid, response, postdata, options) {
alert("success");
},
delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
}
ajaxRowOptions: {
success: function (data, textStatus) {
if(textStatus=="true")
{
alert('success');
}
else
{
alert('failure');
}
}
}
I'm returning true in handler.
Above code is working for me.
Related
I have a problem with .net core 2.0 with datatables.
I am trying to make server side datatable.
Here is my javascript code.
$(document).ready(function () {
$('#myTable').dataTable({
serverSide: true,
paging: true,
searching: true,
lengthMenu: [[10, 25, 50,100], [10, 25, 50,100]],
pageLength: 10,
destroy: true,
ajax: {
type: "POST",
url: "#Url.Action("TableDatas", "Admin")",
datatype: "json",
contentType: 'application/json; charset=utf-8',
data: function (d) {
var postData = {
"request": d,
//Speacial Filter
"status" : "Something i am just trying."
};
return JSON.stringify(postData);
},
dataFilter: function (d) {
return d;
}
},
columns: [
{
name: 'orderid',
data: 'orderid',
title: "Sipariş No",
sortable: false,
searchable: true
},
{
name: 'tmno',
data: "tMNo",
title: "TMNo",
sortable: false,
searchable: true
},
{
name: 'member',
data: "member",
title: "Müşteri",
sortable: false,
searchable: true
},
{
name: 'price',
data: "price",
title: "Tutar",
sortable: false,
searchable: true
},
{
name: 'date',
data: "date",
title: "Sipariş Tarihi",
sortable: false,
searchable: true,
render: function (data, type, full, meta) {
return moment(data).format("DD-MM-YYYY");
}
},
{
name: 'status',
data: "status",
title: "Durum",
sortable: false,
searchable: true
}
]
});
});
Here is the c# action . I am using DataTables nuget for it.
namespace DataTables.AspNet.Core
{
public interface IDataTablesRequest
{
int Draw { get; }
int Start { get; }
int Length { get; }
ISearch Search { get; }
IEnumerable<IColumn> Columns { get; }
IDictionary<string, object> AdditionalParameters { get; }
}
}
[HttpPost]
public IActionResult TableDatas(IDataTablesRequest request,string status)
{
//There are some searchin paging codes...
var response = DataTablesResponse.Create(request,result.TotalCount,result.FilteredCount, finaldata);
return new DataTablesJsonResult(response, true);
}
When i debug script there is a postdata and it converts to Json. There is the data what i want.
There is an image about network tab from browser.
When it comes to action. The datas are null.
I have configuration on my startup.
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
services.RegisterDataTables();
Otherwise when i try to Ajax Get without anything. Like this. It is working.
ajax: "#Url.Action("TableDatas", "Admin")",
But i wanna make post calls because i have custom filters. I need to send extrathings.
I tried [FromBody] etc...
I am missing something but what i dont know.
I am trying to find the information about editurl. Currently, i am working on the framework which does not permit editurl. The calls must go through javascript function which in-turn invokes the component on serverside.
Question is it possible to POST the data to javascript function instead of editurl?
I am experimenting with following:
$(document).ready(function () {
console.log(">>>1");
//--
action.setCallback(this, function(a) {
if (a.getState() === "SUCCESS") {
result = a.getReturnValue();
console.log(result);
//---=
var editActionOptions = {
keys: true,
url:null,
oneditfunc: function (rowid) {
console.log("row with rowid=" + rowid + " is editing.");
},
aftersavefunc: function (rowid, response, options) {
console.log("row with rowid=" + rowid + " is successfuly modified.");
}
};
//-------------------------------------------------------------------------------------------------------
$("#jqGrid").jqGrid({
editurl: 'clientArray',
datatype: "local",
data:result,
colModel: [
{
label: "Edit Actions",
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
},
{
labe: 'ID',
name: 'empid',
width: 75
},
{
label : 'Name',
name: 'Name',
width: 140,
editable: true // must set editable to true if you want to make the field editable
},
{
label: 'dob',
name: 'dob',
width: 100,
editable: true
},
{
label: 'dln',
name: 'dln',
width: 120,
editable: true
}
],
sortname: 'empid',
loadonce: true,
onSelectRow: editRow,
onSave:onSaveRow,
editParams: editActionOptions,
width: 780,
height: 400,
rowNum: 150,
pager: "#jqGridPager"
});
//------------------------------------------------------------------------------------------------------
} else if (a.getState() === "ERROR") {
$A.log("Errors", a.getError());
}
});
$A.enqueueAction(action);
var lastSelection;
function editRow(id) {
console.log(id);
if (id && id !== lastSelection) {
var grid = $("#jqGrid");
grid.jqGrid('restoreRow',lastSelection);
grid.jqGrid('editRow',id, {keys: true} );
lastSelection = id;
}
};
function onSaveRow(id){
console.log(id);
}
The main grid loads fine but When I click on the plus icon the subgrid data does not load, its says loading.... But nothing happens. Don't know what I'm missing. Please help.
Below is the code I'm using:
Controller
namespace SubGrid.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View("Index");
}
RoopaDBEntities db = new RoopaDBEntities();
public JsonResult GetDepts(string sidx, string sord, int page, int rows, string filter)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var DeptsResults = db.Table_Dept.Select(
a => new
{
a.DeptID,
a.DeptName,
a.HOD,
a.Status,
});
int totalRecords = DeptsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "Desc")
{
DeptsResults = DeptsResults.OrderByDescending(s => s.DeptID);
DeptsResults = DeptsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
DeptsResults = DeptsResults.OrderBy(s => s.DeptID);
DeptsResults = DeptsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = DeptsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEmps(string sidx, string sord, int page, int rows, string filter)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var EmpsResults = db.Table_Emp.Select(
a => new
{
a.DeptID,
a.EmpID,
a.EmpName,
a.Gender,
a.Salary,
});
int totalRecords = EmpsResults.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "Desc")
{
EmpsResults = EmpsResults.OrderByDescending(s => s.EmpID);
EmpsResults = EmpsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
EmpsResults = EmpsResults.OrderBy(s => s.EmpID);
EmpsResults = EmpsResults.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
records = totalRecords,
rows = EmpsResults
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
}
}
JavaScript
$(function () {
$("#ListGrid").jqGrid({
url: "../Home/GetDepts/",
datatype: 'json',
mtype: 'Get',
colNames: ['DeptID', 'DeptName', 'HOD', 'Status'],
colModel: [
{ key: true, name: 'DeptID', index: 'DeptID' },
{ key: false, name: 'DeptName', index: 'DeptName' },
{ key: false, name: 'HOD', index: 'HOD' },
{ key: false, name: 'Status', index: 'Status' }
],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30, 40],
height: 225,
sortname: 'DeptID',
sortorder: "desc",
viewrecords: true,
loadonce: true,
ignoreCase: true,
caption: "Department List",
autowidth: true,
multiselect: false,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "0",
},
subGrid: true,
subGridOptions: {
"plusicon": "ui-icon-triangle-1-e",
"minusicon": "ui-icon-triangle-1-s",
"openicon": "ui-icon-arrowreturn-1-e",
},
subGridRowExpanded: function (subgrid_Id, rowid) {
var $subgrid = $("<table id='" + subgrid_Id + "_t'></table>");
$("#" + subgrid_Id)
.append($subgrid);
$subgrid.jqGrid({
url: '../Home/GetEmps/' + '?id=' + rowid,
postData: {
q: 2,
id: rowid,
DeptID: rowid
},
datatype: "json",
mtype: 'Get',
colNames: ['Dept ID', 'Emp ID', 'Emp Name', 'Gender','Salary'],
colModel: [
{ index: 'DeptID', name: 'DeptID' },
{ index: 'EmpID', name: 'EmpID', key: true },
{ index: 'EmpName', name: 'EmpName'},
{ index: 'Gender', name: 'Gender' },
{ index: 'Salary', name: 'Salary' }
],
viewrecords: true,
height: '100%',
autowidth: true,
rowNum: 5,
idPrefix: rowid + "_",
})
},
loadComplete: function () {
$("tr.jqgrow:odd").css("background", "LightBlue");
}
})
.navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true })
});
Index:
#model SubGrid.Models.Dept
#{
ViewBag.Title = "Index";
}
<div>
<table>
<tr>
<td width="100%"><tableid="ListGrid"></table></td>
<td><div id="pager"></div></td>
</tr>
</table>
</div>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/i18n/grid.locale-en.js"></script>
<script src="~/Scripts/Dept.js"></script>
<script src="~/Scripts/jquery.jqGrid.min.js"></script>
<script src="~/Scripts/grid.subgrid.js"></script>
<script src="~/Scripts/jquery.jqGrid.js"></script>
I have a kendo ui grid and in that grid i have a dropdownlist. As for now it works in the way that it gets the name of the customer and adds it to the dropdown but when the dropdown is not "active" it just shows the customerId.
This is my object that i use in the grid:
public int Id { get; set; }
public string Code { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime EndDate { get; set; }
public int MinimumCost { get; set; }
public int MaximumCost { get; set; }
public int Quantity { get; set; }
public Nullable<int> CustomerId { get; set; }
public string CountryCode { get; set; }
public decimal Discount { get; set; }
public string ModelName { get; set; }
What i want to do is a dropdown that is connected to CustomerId but shows customername in the dropdown. This is the code for my grid:
$(document).ready(function () {
var datasource = new kendo.data.DataSource({
transport: {
read: {
url: '/DiscountPromotion/Get',
dataType: "json",
},
update: {
url: '/DiscountPromotion/Update',
dataType: "json",
type: "POST",
contentType: "application/json"
},
destroy: {
url: '/DiscountPromotion/Delete',
dataType: "json",
type: "POST",
contentType: "application/json"
},
create: {
url: '/DiscountPromotion/Add',
dataType: "json",
type: "POST",
contentType: "application/json"
},
parameterMap: function (options, operation) {
if (operation !== "read") {
return JSON.stringify({ discountPromotionDto: options });
}
},
},
pageSize: 10,
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number" },
Code: { type: "string" },
StartDate: { type: "date" },
EndDate: { type: "date" },
MinimumCost: { type: "number", validation: { min: 0 } },
MaximumCost: { type: "number", validation: { min: 0 } },
Quantity: { type: "number", validation: { min: 0 }},
CustomerId: { type: "number" },
CountryCode: { type: "string" },
Discount: { type: "number" },
ModelName: { type: "string" }
}
}
}
});
$("#discountpromotiongrid").kendoGrid({
dataSource: datasource,
batch: true,
toolbar: ["create", "save", "cancel", { name: "genCode", text: "Generate Code", click: function(e) {
return false;
}}],
height: 400,
navigatable: true,
selectable: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
columns: [
{
field: "ModelName",
title: "ModelName",
editor: modelNameDropDown,
template: "#=ModelName#",
width: 150
},
{
field: "Code",
title: "Code",
width: 150
},
{
field: "StartDate",
title: "StartDate",
template: '#= kendo.toString(StartDate,"yyyy-MM-dd") #',
format: "{0:yyyy-MM-dd}",
parseFormats: ["yyyy-MM-dd"],
width: 120
},
{
field: "EndDate",
title: "EndDate",
template: '#= kendo.toString(EndDate,"yyyy-MM-dd") #',
format: "{0:yyyy-MM-dd}",
parseFormats: ["yyyy-MM-dd"],
width: 120
},
{
field: "MinimumCost",
title: "MinCost",
width: 100,
format: "{0:n0}"
},
{
field: "MaximumCost",
title: "MaxCost",
width: 100,
format: "{0:n0}"
},
{
field: "Quantity",
title: "Quantity",
width: 80,
format: "{0:n0}"
},
{
field: "CustomerId",
title: "Customer",
editor: customerDropDown,
template: "#=CustomerId#",
width: 150
},
{
field: "CountryCode",
title: "CountryCode",
editor: countryCodeDropDown,
template: "#=CountryCode#",
width: 120
},
{
field: "Discount",
format: "{0:p0}",
editor: function (container, options) {
$("<input name='Discount'>")
.appendTo(container)
.kendoNumericTextBox(
{
min: 0,
max: 1.0,
step: 0.01
});
},
width: 100
},
{
command: "destroy",
title: " ",
width: 120
}],
editable: true
});
function modelNameDropDown(container, options) {
$('<input required data-text-field="ModelName" data-value-field="ModelName" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
optionLabel: "Select model...",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '/DiscountPromotion/GetModelNamesByCustomerId',
dataType: "json",
type: "POST",
contentType: "application/json"
}
}
}
});
}
function customerDropDown(container, options) {
$('<input required data-text-field="CustomerName" data-value-field="CustomerId" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
optionLabel: "Select model...",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '/DiscountPromotion/GetSuppliersCustomersByCustomerId',
dataType: "json",
type: "POST",
contentType: "application/json"
}
}
}
});
}
function countryCodeDropDown(container, options) {
$('<input required data-text-field="CountryCode" data-value-field="CountryCode" data-bind="value:' + options.field + '"/>')
.appendTo(container)
.kendoDropDownList({
autoBind: true,
optionLabel: "Select model...",
dataSource: {
serverFiltering: true,
transport: {
read: {
url: '/DiscountPromotion/GetCountryCodesBySuppliersCustomers',
dataType: "json",
type: "POST",
contentType: "application/json"
}
}
}
});
}
$(".k-grid-genCode", "#discountpromotiongrid").bind("click", function (ev) {
var text = generateCode();
var grid = $("#discountpromotiongrid").data("kendoGrid");
var row = grid.select();
var data = grid.dataItem(row);
data.dirty = true;
data.Code = text;
$('#discountpromotiongrid').data('kendoGrid').refresh();
//$(".k-grid-edit-row").find("input[name='Code']").val(text);
});
function generateCode() {
var n = 8;
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < n; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
});
The object of the list that the dropdownlist get-method gets looks like this:
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string CountryCode { get; set; }
public string CustomerERPId { get; set; }
So how do i bind the data to CustomerId in the grid but show the value of CustomerName?
The grid doesn't know the customer name which corresponds to a CustomerId. The dropdownlist populates with that list during editing. To make it work you need to load the customers and set the template of the column:
{
field: "CustomerId",
title: "Customer",
editor: customerDropDown,
template: "#=customerNames[CustomerId]#",
width: 150
}
Where customerNames is something like this
var customerNames = { 1: "Foo", 2: "Bar" }; // key is CustomerID value is CustomerName
Please find my code attached :
Jqgrid creation:
<script type="text/javascript">
$(function () {
$("#datagrid").jqGrid({
url: 'jqgridwithwebmethod.aspx/ConvertDataTabletoString',
datatype: 'json',
mtype: 'POST',
serializeGridData: function (postData) {
// return JSON.stringify(postData);
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['Name', 'Age', 'Mobile', 'City', 'Sex', 'FirstName', 'LatName', 'Address', 'Landline'],
colModel: [
{ name: 'Name', index: 'Name', width: 200, frozen: true, editable: true },
{ name: 'Age', index: 'Age', sorttype: 'int', width: 200, editable: true },
{ name: 'Mobile', index: 'Mobile', sorttype: 'int', width: 200, editable: true },
{ name: 'City', index: 'City', width: 200, editable: true },
{ name: 'Sex', index: 'Sex', width: 200, editable: true },
{ name: 'FirstName', index: 'FirstName', width: 200, editable: true },
{ name: 'LastName', index: 'LastName', width: 200, editable: true },
{ name: 'Address', index: 'Address', width: 200, editable: true },
{ name: 'Landline', index: 'Landline', width: 300, editable: true }
],
pager: '#nav',
rowNum: 10,
sortname: 'Name',
autowidth: true,
sortorder: "desc",
shrinkToFit: false,
//forceFit:false,
loadonce: true,
rowList: [10, 20, 30],
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false
//id: "0"
},
caption: 'My first grid'
});
$("#datagrid").jqGrid('setFrozenColumns');
});
**$('#datagrid').jqGrid('navGrid', '#nav',**
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
});
</script>
The function ConvertDataTabletoString is defined as:
[WebMethod]
public static List<Dictionary<string, object>> ConvertDataTabletoString()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select * from studen with(nolock)", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
The Jqgrid use data received from SQL server.
The edit/add/delete icons are not dispalying on the Jqgrid..
Kindly help..
You placed call of navGrid method on the wrong place. You have block $(function () {...}); which meany document ready event handler. You placed call of navGrid method out of the block. It's wrong. You should mode it one line above (directly after the call of setFrozenColumns) to fix the problem.