Not able to Add row using JQGrid - asp.net

Here is the JQGrid setup information
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/TabMaster/GetGridData',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true },
],
pager: jQuery('#pager'),
rowNum: 4,
rowList: [1, 2, 4, 5, 10],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '/scripts/themes/steel/images',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: "/TabMaster/Edit/",
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Company successfully updated");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{},
// Delete options
{url: '/TabMaster/Remove' }
);
});
following is the details for Getting Data and Update Data using JQGrid
#region "JQGrid Actions"
public JsonResult GetGridData(string sidx, string sord, int rows, int page)
{
int pageIndex = page;
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection updateExisting)
{
int _id = Convert.ToInt32(updateExisting["colID"]);
TabMasterViewModel editExisting = new TabMasterViewModel();
editExisting = _tabmasterService.GetSingle(x => x.colID == id);
try
{
UpdateModel(editExisting);
_tabmasterService.Update(editExisting);
return Content("Success");
}
catch (Exception e)
{
return Content(e.Message);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Remove(string id)
{
List<String> ids = new List<String>(id.Split(','));
for (int i = 0; i < ids.Count; i++)
{
int deleteid = Convert.ToInt32(ids[i]);
TabMasterViewModel deleteExisting = new TabMasterViewModel();
deleteExisting = _tabmasterService.GetSingle(x => x.colID == deleteid);
_tabmasterService.Delete(deleteExisting);
}
return RedirectToAction("Index");
}
#endregion
Note:- Get and Update is successfully working but i have problem in ADD and DELETE.
Please anybody help me to write the function for ADD and DELETE?

Here is the complete solution for ADD, EDIT and DELETE
*index.cshtml*
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/TabMaster/GetGridData',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 300, align: 'left', editable: true },
],
pager: jQuery('#pager'),
rowNum: 4,
rowList: [1, 2, 4, 5, 10],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '/scripts/themes/steel/images',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: "/TabMaster/Edit/",
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Company successfully updated");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{url: '/TabMaster/Create', closeAfterAdd: true },
// Delete options
{url: '/TabMaster/Remove' },
{ closeOnEscape: true, multipleSearch: true,
closeAfterSearch: true
}
);
});
controller.cs
#region "JQGrid Actions"
public JsonResult GetGridData(string sidx, string sord, int rows, int page)
{
int pageIndex = page;
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection updateExisting)
{
int _id = Convert.ToInt32(updateExisting["colID"]);
TabMasterViewModel editExisting = new TabMasterViewModel();
editExisting = _tabmasterService.GetSingle(x => x.colID == id);
try
{
UpdateModel(editExisting);
_tabmasterService.Update(editExisting);
return Content("Success");
}
catch (Exception e)
{
return Content(e.Message);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Remove(string id)
{
List<String> ids = new List<String>(id.Split(','));
for (int i = 0; i < ids.Count; i++)
{
int deleteid = Convert.ToInt32(ids[i]);
TabMasterViewModel deleteExisting = new TabMasterViewModel();
deleteExisting = _tabmasterService.GetSingle(x => x.colID == deleteid);
_tabmasterService.Delete(deleteExisting);
}
return RedirectToAction("Index");
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection FormValue)
{
if (ModelState.IsValid)
{
TabMasterViewModel addNew = new TabMasterViewModel();
addNew.FirstName = FormValue["FirstName"];
addNew.LastName = FormValue["LastName"];
_tabmasterService.Add(addNew);
}
return RedirectToAction("Index");
}
#endregion

Related

How to send custom parameter for fetching data using datatables with server side paggination

I am using datatables for fetcing the data from the controller but the issue is that i have to pass some additional parameter for getting the record from the db but the issue is that when i use the sAjaxSource in the datatable request it automatically send all the parameter with the requst like pagination size , columns and sorting and other details without even mentioning it anywhere but when i use the explict ajax request like this.
ajax: {
type: "POST",
data: {accountID : "45d4f5d4f5d"}
}
it only send this parameter which is mentioned in the data and doesn't send other parameter which get sent by default when the request is made using sAjaxSource.
when i send the request like this it works:
$(function () {
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
public ActionResult VoicemailList(JqueryDatatableRequestModel model,string accountId)
{
var totalRecords = 0;
var voicemails = voicemailService.GetVoicemailsListByAccountId(accountId, name: model.sSearch, totalCount: out totalRecords, recordStart: model.iDisplayStart, pageSize: model.iDisplayLength);
var finalResults = Mapper.Map<List<VoicemailModel>>(Voicemails);
return Json(new
{
model.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecords,
aaData = finalResults
}, JsonRequestBehavior.AllowGet);
}`
but when i try to add the additonal parameter it doesnt work
$(function () {
var table = $('#Voicemailtable').DataTable();
var sEcho = table.settings()[0].oAjaxData.sEcho;
var sSearch = table.search();
var iDisplayLength = table.page.len();
var iDisplayStart = table.page.info().start;
var iSortCol_0 = table.order()[0][0];
var sSortDir_0 = table.order()[0][1];
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
ajax: {
url: '#Url.Action("VoicemailList", "Voicemail")',
type: "Get",
data: {
accountId: "45454-df454-f4d65f4d54f"
sEcho: sEcho,
sSearch: sSearch,
iDisplayLength: iDisplayLength,
iDisplayStart: iDisplayStart,
iSortCol_0: iSortCol_0,
sSortDir_0: sSortDir_0
},
},
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
I tried making request from different pattern but its not working if someone could guide my it would be really appriciated.

update/delete event for Kendo UI Grid Aurelia

The update/create/delete events are not getting fired. Any idea?
View:
<ak-grid k-option.bind = "gridOptions" id="adminGrid" k-toolbar.bind="['create']" k-editable.bind="true" k-pageable.bind="true" k-sortable.bind="true">
</ak-grid>
View Model:
activate(params) {
this.name = params.type.toUpperCase();
return this.getData(this.getType(), null).then(items => {
this.getMetadata(items)
.then(metadata => {
this.gridOptions = metadata;
});
});
}
getMetadata(items) {
return new Promise(resolve => {
resolve({
columns: this.getColumns(items),
autoSync: true,
dataSource: {
transport: {
read: //alert("read"),
function (e) {
e.success(items);
},
update:
function (e) {
alert("update"),
e.success(e.data);
},
destroy: function (e) {
alert("delete");
},
parameterMap: function (options, operation) {
if (operation == "create") {
alert("create param");
}
return options;
}
},
pageSize: 10,
editable: true,
pageable: {
refresh: true,
pageSizes: true
}
}
});
});
}

JQgrid is not working in MVC4 and EntityFramework

Hi I started working on JQGrid, I followed the post which I got from an internet blog Jqgrid with MVC
My Code Looks like this:
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<ol class="round">
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '/Home/DynamicGridData',
datatype: 'json',
mtype: 'POST',
colNames: ['UserId', 'FirstName', 'LastName', 'CreatedBy', 'Designation', 'City'],
colModel: [
{ name: 'UserId', index: 'UserId', width: 40, align: 'left' },
{ name: 'FirstName', index: 'FirstName', width: 40, align: 'left' },
{ name: 'LastName', index: 'LastName', width: 400, align: 'left' },
{ name: 'CreatedBy', index: 'CreatedBy', width: 400, align: 'left' },
{ name: 'Designation', index: 'Designation', width: 400, align: 'left' },
{ name: 'City', index: 'City', width: 400, aligh: 'left' }],
pager: jQuery('#pager'),
rowNum: 2,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/content/images',
caption: 'My first grid'
});
});
</script>
<%-- HTML Required--%>
<h2>My Grid Data</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>
</ol>
}
And my Controller looks like this:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Expressions;
using UserInfoGrid.Models;
using System.Linq;
using System.Linq.Dynamic;
namespace UserInfoGrid.Controllers
{
public class HomeController : Controller
{
UserInfoEntities db = new UserInfoEntities();
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.Users.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
// var userInfo = db.User(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
//var userInfo = db.Users.OrderBy((sidx+""+sord).Skip(pageIndex * pageSize).Take(pageSize)).ToList();
var userInfo = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from u in userInfo
select new
{
i = u.UserId,
cell = new string[] { u.UserId.ToString(), u.FirstName, u.LastName, u.CreatedBy.ToString(), u.Designation, u.City.ToString() }
//cell = new string[] { "", "", "", "" }
}).ToArray()
};
return Json(jsonData);
}
}
}
}
The problem is, nothing is displaying in Index page. I am tired of trying, please help me. If you find any flaws in my code.
Thanks in advance
Please try is as below.
[HttpPost]
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
//your code here
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
Change this url: '/Home/DynamicGridData' to this url: '#Url.Action("DynamicGridData")'

Data is not Displaying in Jqgrid In Asp.net using Web Services

I am using Jqgrid to display my data into jqgrid using web services in asp.net...but it is loading only when I am giving limit in the query.If I want to load all the data using second commneted query in the code then its not loading and giving error ""Message":"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property."
Here is my entire Module Architecture...
index.aspx page...
<script type="text/javascript">
$(function () {
$("#table").jqGrid({
datatype: function (pdata) { getData(pdata); },
height: 500,
colNames: ['username', 'ordinal', 'authcode', 'extension', 'trunk', 'dialnumber', 'dialdate', 'dialtime', 'duration', 'destination', 'price', 'toc'],
colModel: [
{ name: 'username', width: 100, sortable: true, align: 'center' },
{ name: 'ordinal', width: 100, sortable: true, align: 'center' },
{ name: 'authcode', width: 100, sortable: true },
{ name: 'extension', width: 100, sortable: true, align: 'center' },
{ name: 'trunk', width: 100, sortable: true, align: 'center' },
{ name: 'dialnumber', width: 100, sortable: true, align: 'center' },
{ name: 'dialdate', width: 100, sortable: true, align: 'center' },
{ name: 'dialtime', width: 100, sortable: true, align: 'center' },
{ name: 'duration', width: 100, sortable: true, align: 'center' },
{ name: 'destination', width: 100, sortable: true, align: 'center' },
{ name: 'price', width: 100, sortable: true, align: 'center' },
{ name: 'toc', width: 100, sortable: true, align: 'center' }
],
rowNum: 100,
rowList: [100, 200, 300],
pager: '#UsersGridPager',
sortname: 'username',
sortable: true,
viewrecords: true,
sortorder: 'asc',
shrinkToFit: false,
rownumbers: true,
loadtext: 'Loading..'
});
jQuery("#table").jqGrid('navGrid', '#UsersGridPager', { add: false, edit: false, del: false, search: true, refresh: true });
});
function getData(pData) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
data: '{}',
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success")
ReceivedClientData(JSON.parse(getMain(data)).rows);
},
error: function (data, textStatus) {
alert('An error has occured retrieving data!');
}
});
}
function ReceivedClientData(data) {
var thegrid = $("#table");
thegrid.clearGridData();
for (var i = 0; i < data.length; i++)
thegrid.addRowData(i + 1, data[i]);
}
function getMain(dObj) {
if (dObj.hasOwnProperty('d'))
return dObj.d;
else
return dObj;
}
</script>
JsonHelper.cs file
// Convert Object to Json String
// <param name="obj">The object to convert</param>
// <returns>Json representation of the Object in string</returns>
public static string ToJson(object obj)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
}
public static List<Person> GetPersons()
{
List<Person> persons = new List<Person>();
string connectionString = "Server=localhost;Port=3306;Database=projecttt;UID=root;Pwd=techsoft;pooling=false";
MySqlConnection conn;
conn = new MySqlConnection(connectionString);
conn.Open();
string s = "SELECT username,ordinal,authcode,extension,trunk,dialnumber,dialdate,dialtime,duration,destination,price,toc FROM processeddata_table order by username limit 0,200";
// string s = "SELECT username,ordinal,authcode,extension,trunk,dialnumber,dialdate,dialtime,duration,destination,price,toc FROM processeddata_table ";
MySqlCommand cmd = new MySqlCommand(s,conn);
cmd.ExecuteNonQuery();
using (MySqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
persons.Add(new Person()
{
username = Convert.ToString(dr["username"]),
ordinal = Convert.ToString(dr["ordinal"]),
authcode = Convert.ToString(dr["authcode"]),
extension = Convert.ToString(dr["extension"]),
trunk = Convert.ToString(dr["trunk"]),
dialnumber = Convert.ToString(dr["dialnumber"]),
dialdate = Convert.ToString(dr["dialdate"]),
dialtime = Convert.ToString(dr["dialtime"]),
duration = Convert.ToString(dr["duration"]),
destination = Convert.ToString(dr["destination"]),
price = Convert.ToString(dr["price"]),
toc = Convert.ToString(dr["toc"])
});
}
}
return persons;
}
}
PagedList.cs File
IEnumerable _rows;
int _totalRecords;
int _pageIndex;
int _pageSize;
object _userData;
public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
{
_rows = rows;
_totalRecords = totalRecords;
_pageIndex = pageIndex;
_pageSize = pageSize;
_userData = userData;
}
public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
: this(rows, totalRecords, pageIndex, pageSize, null)
{
}
public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }
public int page { get { return _pageIndex; } }
public int records { get { return _totalRecords; } }
public IEnumerable rows { get { return _rows; } }
public object userData { get { return _userData; } }
public override string ToString()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this);
}
}
webservices.cs
[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
List<Person> persons = JsonHelper.GetPersons();
return Newtonsoft.Json.JsonConvert.SerializeObject(new PagedList(persons, persons.Count, 1, persons.Count));
}
}
Person.cs
public string username { get; set; }
public string ordinal { get; set; }
public string authcode { get; set; }
public string extension { get; set; }
public string trunk { get; set; }
public string dialnumber { get; set; }
public string dialdate { get; set; }
public string dialtime { get; set; }
public string duration { get; set; }
public string destination { get; set; }
public string price { get; set; }
public string toc { get; set; }
Plz guys Help me .THanx in advance..
Why are you using ExecuteNonQuery() for select ? try ExecuteReader() method.
See this :- Question on MaxJsonLength
For local pagination loadonce: true can be used but still you will get the same error as you are trying to load too much data which is not advised. Also, ajax requests are used to handle small amount of data

jqgrid edit call ajax every time

I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si รจ verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid
You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.

Resources