I have view showing a list of documents using jqgrid. While I click on the document title in the grid, I created a pop up with partial view and in this partial view up am using Kendo tabs. In one of the tab am using a partial view to load a jqgrid which shows all the Document logs and in this grid my navgrid is not working. When i click on the next button for navigating to next page, it is actually navigating the main page where I have the list of documents. To avoid confusion I used different 'id' for the navgrid in the partial view, but then it showed no next and previous button at all. Could anyone guide me how to add paging to the partial view while not affecting the parent view.
Below is jqgrid code of the main View:
$.ajax(
{
type: "GET",
url: "#Url.Action("GetDocumentFileList", "Document")",
data: "",
dataType: "json",
success: function (data) {
if (data == "SessionTimeOut")
window.location.href = '#Url.Action("SessionTimeOut", "Error")';
var page = data.Page;
var rows = data.Rows;
var colModel = eval(data.Columns);
var colNames = eval(data.ColumnsTitle);
var $grid = $("#datagrid");
$grid.jqGrid({
url: "#Url.Action("GetDocumentFileList", "Document")",
datatype: griddataType,
datastr: rows,
colNames: colNames,
colModel: colModel,
gridComplete: initGrid,
rowList: [25, 50, 75, 100],
ignoreCase: true,
width: null,
shrinkToFit: true,
multiselect: true,
multiboxonly: false,
pager: '#navGrid',
sortname: 'DocumentRegisterID',
sortorder: "desc",
scrollerbar: true,
viewrecords: true,
rowNum: 25,
autowidth: true,
ondblClickRow: function (DocumentRegisterID) {
if (DocumentRegisterID && DocumentRegisterID !== lastsel2) {
$grid.jqGrid('restoreRow', lastsel2);
$grid.jqGrid('editRow', DocumentRegisterID, true, null, successFuncStandardGrid);
lastsel2 = DocumentRegisterID;
}
},
editurl: "#Url.Action("EditDocumentNo", "Document")",
hoverrows: true,
onSelectRow: function () {
return false;
},
here is the jqgrid code for the partial view used in the pop up in main view :
$.ajax(
{
type: "GET",
url: "#Url.Action("DocHistoryEventLog", "Document")",
data: '',
success: function (data) {
var page = data.Page;
var rows = data.Rows;
var $grid = $("#dataeventgrid");
$grid.jqGrid({
url: "#Url.Action("DocumentRegisterHistoryEventLogList", "Document", new { id = #docId })",
datatype: "json",
datastr: rows,
colNames: ['DocumentRegisterEventLogID', 'Event Type', 'Description', 'Revision', 'Version', 'Log By', 'Log Date', 'Organization Name', 'Document Owner Organization'],
colModel: [
{ name: 'DocumentRegisterEventLogID', index: 'DocumentRegisterEventLogID', key: true, hidden: true },
{ name: 'EventType', index: 'EventType', width: "20%", resizable: true },
{ name: 'EventDescription', index: 'EventDescription', sorttype: 'text', width: "20%", resizable: true },
{ name: 'Revision', index: 'Revision', width: "15%", sorttype: 'text', resizable: true },
{ name: 'DocVersion', index: 'DocVersion', width: "20%", resizable: true },
{ name: 'LogBy', index: 'LogBy', sorttype: 'text', width: "20%", resizable: true },
{
name: 'StrLogDate', index: 'StrLogDate', sorttype: 'text', width: "25%", resizable: true,
searchoptions: { sopt: ["eq", "ne", "lt", "le", "gt", "ge"], dataInit: initDatepicker },
},
{ name: 'OrganizationName', index: 'OrganizationName', sorttype: 'text', width: "20%", resizable: true },
{ name: 'DocumetOwnerOrganizationName', index: 'DocumetOwnerOrganizationName', width: "20%", sorttype: 'text', resizable: true },
],
rowList: [15, 30, 45, 100],
loadonce: false,
shrinkToFit: true,
ignoreCase: true,
pager: '#navLogGrid',
autoencode: true,
sortname: 'DocumentRegisterEventLogID',
sortorder: "desc",
viewrecords: true,
rowNum: 15,
width: 850,
height:270,
gridview: true,
height: "auto",
scrollerbar: true,
loadComplete: function () {
highlightFilteredData.call(this);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
});
$grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn", stype: 'select' });
$grid.jqGrid("navGrid", "#navLogGrid", { add: false, edit: false, del: false, search: false, refresh: true });
$grid.parents('div.ui-jqgrid-bdiv').css("max-height", '270px');
Setting the property loadonce:true in my partial view solved my problem. Thanks
Related
I am having issues with Free Jqgrid where I can not get it to post to my developer version of Microsoft SQL server. I am using Microsoft visual studios. I am using entity framework 6 for the database connections. When I use break points it doesn't seem to hit my createbid, editbid, or delete bid. I also don't get any errors in console.
I have looked through and done many of the tutorials for editing updating and adding lines. I had the same problem. I cant find an answer that works on stack overflow through my research.
I published it to IIS to see if maybe it was something with visual studios and to see if anything changes but i did get some errors this time. It is not finding the /Home/GetBidValues, Home/EditBid, /Home/CreateBid, /Home/DeleteBid. this is weird because with visual studios it was at least getting data into the grid and showing it. So I will look into this further and see if there is something wrong with my ajax and also with my C# code.
Here is my Jquery file
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['Client Cost', 'ElementId', 'Note', 'Area', 'Element', 'Item', 'Qty', 'Description'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
{
key: true,
hidden: true,
name: 'ElementId',
index: 'ElementId',
frozen: true,
editable: false
}, {
key: false,
name: 'Note',
index: 'Note',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Area',
index: 'Area',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Element',
index: 'Element',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
name: 'Item',
index: 'Item',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'QTY',
index: 'QTY',
frozen: true,
editable: true,
width: 70,
align: 'center'
}, {
key: false,
name: 'Description',
index: 'Description',
frozen: true,
editable: true,
width: 70,
align: 'center'
}],
pager: '#pager',
gridview: true,
ignoreCase: true,
rowNumbers: false,
shrinkToFit: false,
height: '100%',
width: 1000,
viewrecords: true,
footerrow: true,
emptyrecords: 'No records to display',
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
}
});
$('#grid').jqGrid( 'inlineNav','#pager', {
edit: true,
add: true,
del: true,
cancel: true,
search: true,
refresh: true,
editparams: {
keys:true
}
}, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
},{//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
Here is my C# file
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ERPWebAppTest.Models;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
namespace ERPWebAppTest.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
Test1Entities db = new Test1Entities();
[HttpGet]
public JsonResult GetBidValues(string sidx, string sord, int page, int rows)
{
//old code
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
var Results = db.BidDetails.Select(
a => new
{
a.ElementID,
a.Note ,
a.Area ,
a.Element ,
a.Item ,
a.QTY ,
a.Descr ,
});
int totalRecords = Results.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
Results = Results.OrderByDescending(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
Results = Results.OrderBy(s => s.ElementID);
Results = Results.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = Results
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string CreateBid([Bind(Exclude = "ElementID")] BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.BidDetails.Add(obj);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfully";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string EditBid(BidDetail obj)
{
Test1Entities db = new Test1Entities();
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(obj).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
[HttpPost]
public string DeleteBid(int ElementID)
{
Test1Entities db = new Test1Entities();
BidDetail list = db.BidDetails.Find(ElementID);
db.BidDetails.Remove(list);
db.SaveChanges();
return "Deleted successfully";
}
}
}
I see many small small issues into your jqgrid code, which can be one of the reason of your current problem. You can change them in order to make the above code workable.
colModel items numbers are not exactly same as colNames items. You wrote Client Cost at first in colNames but in colModel you haven't used that.
You also haven't pasted your html code which is required to point jqgrid to load on table element.
for example:
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
I am also assuming that you have already added free-jqgrid scripts and jquery-ui css files.
Also, in your c# code you can remove redundancy by using a global db initialization.
I have created a demo jqgrid which you can alter according your requirement:
<div class="row">
<table id="grid" class="table table-bordered"></table>
<div id="pager"></div>
</div>
#section Scripts{
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/free-jqGrid/jquery.jqgrid.min.js"></script>
<script type="text/javascript">
$(function () {
$("#grid").jqGrid
({
url: "/Home/GetBidValues",
datatype: 'json',
mtype: 'Get',
colNames: ['LanguageId', 'LanguageName', 'LanguageDescription', 'CreatedBy', 'CreatedOn'], //Othr Misc
//colModel takes the data from controller and binds to grid
colModel: [
//{ name: "act", template: "actions", align: "left", width: 58 },
{
key: true,
hidden: true,
name: 'LanguageId',
index: 'LanguageId',
editable: false
}, {
key: false,
name: 'LanguageName',
index: 'LanguageName',
frozen: true,
editable: true,
align: 'center'
}, {
key: false,
name: 'LanguageDescription',
index: 'LanguageDescription',
editable: true,
align: 'center'
}, {
key: false,
name: 'CreatedBy',
index: 'CreatedBy',
editable: true,
align: 'center'
}, {
name: 'CreatedOn',
index: 'CreatedOn',
editable: true,
align: 'center'
}],
//cmTemplate: { editable: true, autoResizable: true },
iconSet: "fontAwesome",
rowNum: 10,
//autoResizing: { compact: true },
rowList: [5, 10, 20, "10000:All"],
viewrecords: true,
pager: jQuery('#pager'),
toppager: false,
inlineEditing: { keys: true, position: "afterSelected" },
rownumbers: true,
sortname: "invdate",
sortorder: "desc",
caption: "Demonstration of the usage custom action buttons",
autowidth: true,
shrinkToFit: false,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "LanguageId"
}
});
jQuery("#grid").jqGrid('filterToolbar', { stringResult: true, searchOnEnter:
false, defaultSearch: "cn", multipleSearch: true, searchOperators: true, search: true
}); //searchOnEnter: false means records are filtered as soon as the text is
entered by the user
jQuery("#grid").jqGrid('navGrid', '#pager', { add: true, edit: true, del: true, search: true, refresh: true,view:true }, {
// edit options
zIndex: 100,
url: '/Home/EditBid',
//datatype: 'json',
//mtype: 'Post',
closeOnEscape: true,
closeAfterEdit: true,
recreateForm: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {//add
zIndex: 100,
url: "/Home/CreateBid",
closeOnEscape: true,
closeAfterAdd: true,
reloadaftersubmit: true,
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
}, {
// delete options
zIndex: 100,
url: "/Home/DeleteBid",
closeOnEscape: true,
closeAfterDelete: true,
recreateForm: true,
reloadaftersubmit: true,
msg: "Are you sure you want to delete this task?",
afterComplete: function (response) {
if (response.responseText) {
alert(response.responseText);
}
}
});
});
</script>
}
I am writing code for doing inline editing in jqgrid. It's working fine in the pop-up mode. But I need the same in the inline mode. Please help me solve this problem. I have been trying to solve it for the past week.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="JQGridReq/jquery-1.9.0.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" />
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/javascript"></script>
<script src="JQGridReq/grid.locale-en.js" type="text/javascript"></script>
<script src="JQGridReq/jquery.jqGrid.js" type="text/javascript"></script>
<link href="JQGridReq/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script src="Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="topList">
</div>
<table id="list">
</table> <%--for grid--%>
<div id="pager">
</div> <%--for paging--%>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
function getCountry() {
var country;
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
async: false,
url: "Default.aspx/getNational",
dataType: "json",
success: function (data) {
country = data.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
return country;
}
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "Default.aspx/getEmployee",
dataType: "json",
success: function (data) {
data = data.d;
$("#list").jqGrid({
datatype: "local",
colNames: ['', 'Employee Id', 'Name', 'Email', 'Phone', 'Password', 'Nationality', 'Date of Birth'],
colModel: [
{
name: 'act', index: 'act', width: 75, align: 'center', search: false, sortable: false, formatter: 'actions',
formatoptions: {
keys: true,
editformbutton: true,
editOptions: {
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
closeAfterEdit: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
alert(postData);
return JSON.stringify(postdata);
}
},
delOptions:
{
ajaxDelOptions: { contentType: "application/json" },
reloadAfterSubmit: false,
onclickSubmit: function (eparams) {
var retarr = {};
var sr = $("#list").getGridParam('selrow');
rowdata = $("#list").getRowData(sr);
retarr = { employeeId: rowdata.employeeId };
return retarr;
},
serializeDelData: function (postdata) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
} // we want use [Enter] key to save the row and [Esc] to cancel editing.
}
},
{ name: 'employeeId', index: 'employeeId', width: 55, stype: 'text', sortable: true, editable: true, formoptions: { rowpos: 1, colpos: 1 }, editrules: { integer: true } },
{ name: 'name', index: 'name', width: 90, stype: 'text', sortable: true, editable: true, editrules: { required: true }, formoptions: { rowpos: 2, colpos: 1 } },
{ name: 'email', index: 'email', width: 90, stype: 'text', sortable: true, editable: true, editrules: { email: true, required: true }, formoptions: { rowpos: 2, colpos: 2 } },
{ name: 'phone', index: 'phone', width: 70, align: "right", stype: 'text', sortable: true, editable: true, formoptions: { rowpos: 0, colpos: 0 } },
{ name: 'pwd', index: 'pwd', width: 70, align: "right", stype: 'text', edittype: 'password', sortable: true, editable: true, formoptions: { rowpos: 3, colpos: 2 } },
{
name: 'nationalId', index: 'nationalId', width: 80, align: "right", formatter: 'select', stype: 'select',
editable: true, edittype: "select", editoptions: { value: getCountry() }, formoptions: { rowpos: 4, colpos: 1 }
},
{
name: 'dateOfBirth', index: 'dateOfBirth', width: 80, align: "right",
edittype: 'text', editable: true,
editoptions: {
dataInit: function (el) {
$(el).datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
});
}
},
formoptions: { rowpos: 4, colpos: 2 }
}
],
//this line is used to pass the data into the database
//
data: JSON.parse(data),
rowno: 10,
loadonce: true,
/* multiselect:true,*/
rowlist: [5, 10, 20],
pager: '#pager',
viewrecords: true,
gridview: true,
sortorder: 'asc',
toppager: true,
cloneToTop: true,
altrows: true,
autowidth: false,
hoverrows: true,
height: 300,
/* toolbar: [true, "top"],*/
rownumbers: true,
caption: "Employee Data",
editurl: 'Default.aspx/EditUpdateDel'
/* ondblClickRow: function(rowid) {
$(this).jqGrid('editGridRow', rowid,
{recreateForm:true,closeAfterEdit:true,
closeOnEscape:true,reloadAfterSubmit:false, width: 500});
}*/
});
$('#list').jqGrid('navGrid', '#pager',
{
edit: true,
add: true,
del: true,
search: false,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
cloneToTop: true
}
, {
//add//
recreateForm: true,
//reloadAfterSubmit: false,
//beforeShowForm: function (form) {
// $('#tr_employeeId', form).hide();
//},
width: 500,
reloadAfterSubmit: false,
closeAfterAdd: false,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
//edit//
//Here i ham writing a code for doing inline editing in jqgrid. It's working //fine in the pop-up mode.But i need the same in the inline mode.pls help me //solve this problem. I a trying to solve it for the past on week.
{
//recreateForm: true,
//beforeShowForm: function (form) {
// $('#tr_employeeId', form).hide();
//},
//width: 500,
//reloadAfterSubmit: false,
//closeAfterAdd: false,
//ajaxEditOptions: { contentType: "application/json" },
//serializeEditData: function (postData) {
// var postdata = { 'data': postData };
// return JSON.stringify(postdata);
//}
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
closeAfterEdit: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
{
//delte//
ajaxDelOptions: { contentType: "application/json" },
reloadAfterSubmit: false,
onclickSubmit: function (eparams) {
var retarr = {};
var sr = $("#list").getGridParam('selrow');
rowdata = $("#list").getRowData(sr);
retarr = { employeeId: rowdata.employeeId };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
$("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true });
var grid = $("#list");
var topPagerDiv = $('#' + grid[0].id + '_toppager')[0];
$("#" + grid[0].id + "_toppager_center", topPagerDiv).remove(); /"#list_toppager_center"/
$(".ui-paging-info", topPagerDiv).remove();
var bottomPagerDiv = $("div#pager")[0];
$("#add_" + grid[0].id, bottomPagerDiv).remove();
$("#edit_" + grid[0].id, bottomPagerDiv).remove();
$("#del_" + grid[0].id, bottomPagerDiv).remove();
$("#refresh_" + grid[0].id, bottomPagerDiv).remove();
// "#add_list"
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
</script>
</body>
</html>
There are a lot of places in the code which could be better to change, but your main problem is wrong usage of formatoptions for formatter: 'actions'.
You can read in the documentation of the option of formatter: 'actions'the following:
When the editformbutton parameter is set to true the form editing
dialogue appear instead of in-line edit. The option editOptions will
be used only for the form editing.
You try to use inline editing, so you have to remove editformbutton: true property from formatoptions first of all.
To serialize the data one should use serializeRowData callback of jqGrid instead of usage serializeEditData callback of the form editing
Some common remarks to your code.
I recommend you to move the <script> part where you create the grid from the <body> to the <head> part. Alternatively you can remove $(document).ready(function () {...}); handler. The usage of ready for body inside of the body is not good.
It seems that employeeId is the native id of the data which you load. You can add key: true to employeeId column or to use jsonReader: {id: "employeeId" } (or jsonReader: {id: 0 } depend on exact format of input data which you use).
You use data: JSON.parse(data.d), where data is the parameter of success callback. It means that you made unneeded JSON serialization in "Default.aspx/getEmployee". Instead of returning object you probably convert the object with data to string manually. DotNet framework *automatically convert the returned data to JSON. So you should remove manual conversion of returned data to string inside of "Default.aspx/getEmployee". After that you need replace data: JSON.parse(data.d) to data: data.d. Now you can remove manual $.ajax call to the usage of datatype: "json" and url: "Default.aspx/getEmployee" and to use just jsonReader: {root: "d.rows", page: "d.page", total: "d.total", records: "d.records"}. If you don't use server side paging then you should add loadonce: true option additionally
There are some other places to improve the code, but one can't solve all problems at once.
I have implemented the JqGrid in my application. I have done the edit,delete, insert operations but I am failing in searching the records. I have bind the data from the sql server.
Here is my script
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery.extend(jQuery.jgrid.edit, {
closeAfterEdit: true,
closeAfterAdd: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata); ;
}
});
jQuery.extend(jQuery.jgrid.del, {
ajaxDelOptions: { contentType: "application/json" },
onclickSubmit: function (eparams) {
var retarr = {};
var sr = jQuery("#contactsList").getGridParam('selrow');
rowdata = jQuery("#contactsList").getRowData(sr);
retarr = { PID: rowdata.PID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
$.extend($.jgrid.defaults,
{ datatype: 'json' }
);
jQuery.extend(jQuery.jgrid.search, {
});
$("#contactsList").jqGrid({
url: '/WebService.asmx/GetListOfPersons1',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true },
editoptions: { value: getAllSelectOptions() }
}],
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'PID',
sortorder: "asc",
pager: jQuery('#gridpager'),
viewrecords: true,
gridview: true,
height: '100%',
editurl: '/WebService.asmx/EditRow',
// searchurl: '/WebService.asmx/Searchrow',
caption: 'Person details'
}).jqGrid('navGrid', '#gridpager', { edit: true, add: true, del: true, search: true });
jQuery("#contactsList").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, searchOperators: true });
// jQuery("#contactsList").setGridParam({ data: results.rows, localReader: reader }).trigger('reloadGrid');
jQuery("#contactsList").jqGrid('setGridParam', { url: "WebService.asmx/searchrow", page: 1 }).trigger("reloadGrid");
});
function getAllSelectOptions() {
var states = { 'male': 'M', 'female': 'F' };
return states;
}
</script>
Here I have given the reference for searching in my asmx file like WebService.asmx/searchrow when I click the find button in the popup the cursor is moving to the specified method in the url.
Here is my question how can I get the user entered search parameter name and value to that method to perform the search operation .
I have defined the searchrow method like following
[WebMethod]
public List<Person> searchrow(HttpContext context)
{
return null;
}
Please help me to out from this problem or any other alternative to do the search operation in JQGrid.
thanks
purna
I need to extract the data "FechaCaducidad" from the grid "FarmacoGrid" to store it in an auxiliary variable "fechaCadAux". I tried to do it several different ways but have not been successful.
$(document).ready(function () {
$("#FarmacoGrid").jqGrid({
url: '#Url.Action("Load", "Farmaco")',
datatype: 'json',
mtype: 'POST',
autowidth: true,
altRows: true,
altclass: 'grid-alt-row',
rowNum: #(ViewBag.PageSize * (ViewBag.PageIndex + 1)),
colNames: ['NomFarmaco', 'Cantidad', 'FechaCaducidad', 'FechaPedido','FechaReposicion', '', '', '', ''],
colModel: [
{ index: 'NomFarmaco', name: 'NomFarmaco', sortable: true, resizable: false },
{ index: 'Cantidad', name: 'Cantidad', sortable: true, resizable: false },
{ index: 'FechaCaducidad', name: 'FechaCaducidad', sortable: true, resizable: false },
{ index: 'FechaPedido', name: 'FechaPedido', sortable: true, resizable: false },
{ index: 'FechaReposicion', name: 'FechaReposicion', sortable: true, resizable: false },
{ name: 'imagen', sortable: false, classes: 'grid-cell-imagen', resizable: false },
{ name: 'fechaCadAux', sortable: false, classes: 'grid-cell-fechaCadAux', resizable: false },
{ name: 'fechaHoyAux', sortable: false, classes: 'grid-cell-fechaHoyAux', resizable: false },
{ name: 'edit', sortable: false, classes: 'grid-cell-edit', resizable: false },
],
gridComplete:
function(){
var ids = jQuery("#FarmacoGrid").jqGrid('getDataIDs');
for(var i=0;i < ids.length;i++)
{
var rowId = ids[i];
var fechaCadAux = $("#FarmacoGrid"+FechaCaducidad).val();
var fechaHoyAux = Date.parse(new Date());
var imagenHtml = imagenHtml = '<img src="#Url.Content("~/Content/Images/verde.png")"/>';
var editHtml = '<img src="#Url.Content("~/Content/Images/CRUD/edit.png")"/>';
var deleteHtml = '<img src="#Url.Content("~/Content/Images/CRUD/delete.png")"/>';
$("#FarmacoGrid").jqGrid('setRowData', ids[i], { imagen: imagenHtml, "fechaCadAux": fechaCadAux, "fechaHoyAux": fechaHoyAux, "edit": editHtml, "delete": deleteHtml});
}
The solution for my own question is:
var fechaCadAux = jQuery("#FarmacoGrid").jqGrid('getRowData',rowId).FechaCaducidad;
This is the code I am using to load my jqGrid:
function getTopics() {
var fid = document.getElementById("SelectFunction").value;
//alert(fid);
$.ajax({
url: "Restful.svc/GetTopics",
data: { functionID: fid },
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data, status, xHR) {
var thegrid = jQuery("#editgrid")[0];
thegrid.addJSONData(JSON.parse(data.d));
$("#editgrid").fluidGrid({ example: "#outerContainer", offset: -10 });
},
error: function (xHR, status, err) {
alert("ERROR: " + status + ", " + err);
}
});
}
function LoadDataIntoGrid() {
var lastcell;
jQuery("#editgrid").jqGrid('GridUnload');
jQuery("#editgrid").jqGrid({
datatype: getTopics,
height: '300px',
colNames: ['TopicID', 'Topic', 'Description', 'Topic Entity', 'Inactive'],
colModel: [
{ name: 'TopicID', index: 'TopicID', width: 200, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'TopicCode', index: 'TopicCode', width: 100, editable: true, editoptions: { size: 10} },
{ name: 'TopicDescription', index: 'TopicDescription', width: 200, editable: true, editoptions: { size: 30} },
{ name: "TopicEntity", index: "TopicEntity", width: 200, editable: true, resizable: true, edittype: "select", editoptions: { value: returnEntityList()} },
{ name: 'Inactive', index: 'Inactive', width: 60, align: "center", editable: true, edittype: "checkbox", formatter: 'checkbox', formatoptions: { disabled: true} }
],
rowNum: 30,
rowList: [10, 20, 30],
pager: $('#pagernav'),
sortname: 'Topic',
viewrecords: true,
sortorder: "desc",
caption: "Topics",
editurl: "Restful.svc/SaveTopic",
onSelectRow: function (id) {
if (id && id !== lastcell) {
jQuery('#editgrid').jqGrid('restoreRow', lastcell);
jQuery('#editgrid').jqGrid('editRow', id, true);
lastcell = id;
}
}
}).navGrid('#pagernav', { edit: false, add: true, del: false });
}
Everything loads properly, and clicking on a row makes the fields editable like it should. When the enter key is pressed to save the edits the event seems to fire properly, and calls the "SaveTopic" method referenced in the editurl property. At this point I get an error.
If SaveTopic is defined like this:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic( string TopicCode, string TopicDescription, string TopicEntity, string Inactive, string oper, string id)
{
//Code Here
}
I get this error from jqGrid: "Error Row: 3 Result: 500:Internal Server Error Status: error"
If SaveTopic is defined like this(Method changed to GET):
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic( string TopicCode, string TopicDescription, string TopicEntity, string Inactive, string oper, string id)
{
//Code Here
}
I get this error from jqGrid: "Error Row: 3 Result: 405:Method Not Allowed Status: error"
I can't find anyone else having this problem, and according to the similar example I could find I seem to be doing it correctly. All help is greatly appreciated at this point.
WCF Services only allow HTTP Post requests: Hence they are not RESTFul otherwise they would pass data via the URL in a GET Request.
Your method says it accepts individual items ie a lot of strings. This is incorrect, automatic JSon binding isn't smart enough to bind each item separately. Try creating an information agent with the correct properties and receive that or a JSONResult object and parsing the data yourself. If you rely on automatic binding make sure to use the latest version of the .NET frame work either 3.5 SP1 or higher in which automatic JSon to Model binding is allowed.
Sources: Asp.net, Microsoft MVC 3.0 reference guide, msdn, trirand.com, ect.
I finally managed to to make it work using this work around. It isn't ideal, but it gets the job done. Code changes in bold.
function getTopics()
var fid = document.getElementById("SelectFunction").value;
//alert(fid);
$.ajax({
url: "Restful.svc/GetTopics",
data: { functionID: fid },
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data, status, xHR) {
var thegrid = jQuery("#editgrid")[0];
thegrid.addJSONData(JSON.parse(data.d));
$("#editgrid").fluidGrid({ example: "#outerContainer", offset: -10 });
},
error: function (xHR, status, err) {
alert("ERROR: " + status + ", " + err);
}
});
}
function LoadDataIntoGrid() {
var lastcell;
jQuery("#editgrid").jqGrid('GridUnload');
jQuery("#editgrid").jqGrid({
datatype: getTopics,
**ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },**
height: '300px',
colNames: ['TopicID', 'Topic', 'Description', 'Topic Entity', 'Inactive'],
colModel: [
{ name: 'TopicID', index: 'TopicID', width: 200, editable: false, editoptions: { readonly: true, size: 10} },
{ name: 'TopicCode', index: 'TopicCode', width: 100, editable: true, editoptions: { size: 10} },
{ name: 'TopicDescription', index: 'TopicDescription', width: 200, editable: true, editoptions: { size: 30} },
{ name: "TopicEntity", index: "TopicEntity", width: 200, editable: true, resizable: true, edittype: "select", editoptions: { value: returnEntityList()} },
{ name: 'Inactive', index: 'Inactive', width: 60, align: "center", editable: true, edittype: "checkbox", formatter: 'checkbox', formatoptions: { disabled: true} }
],
rowNum: 30,
rowList: [10, 20, 30],
pager: $('#pagernav'),
sortname: 'Topic',
viewrecords: true,
sortorder: "desc",
caption: "Topics",
editurl: "Restful.svc/SaveTopic",
onSelectRow: function (id) {
if (id && id !== lastcell) {
jQuery('#editgrid').jqGrid('restoreRow', lastcell);
jQuery('#editgrid').jqGrid('editRow', id, true);
lastcell = id;
}
}
}).navGrid('#pagernav', { edit: false, add: true, del: false });
}
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public void SaveTopic() {
**int FunctionID = Convert.ToInt32(HttpContext.Current.Request.Form["FunctionID"]);
int TopicID = Convert.ToInt32(HttpContext.Current.Request.Form["TopicID"]);
string TopicCode = HttpContext.Current.Request.Form["TopicCode"];
string TopicDescription = HttpContext.Current.Request.Form["TopicDescription"];
int TopicEntity = Convert.ToInt32(HttpContext.Current.Request.Form["TopicEntity"]);
string Inactive = HttpContext.Current.Request.Form["Inactive"];
string oper = HttpContext.Current.Request.Form["oper"];
string id = HttpContext.Current.Request.Form["id"];**
//Code here
}