Retrieve values from the database with jquery - c#

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;

Related

Jqgrid is not able to add, edit or delete into my instance of SQL server and I don't think it is even hitting the add, edit or delete function

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>
}

jqgrid navgrid not working inside tabs

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

Edit and add features functionality not working in jqgrid

Class that carries out CRUD functionality with a help of a stored proc
public class InsertUpdateDeleteBLL
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
SqlCommand com = new SqlCommand();
public string InsertUpdateDeleteMethod(object param)
{
string returnValue = "";
try
{
Dictionary<string,> editData = param as Dictionary<string,>;
com.CommandText = "InsertUpdateDeleteSP";
com.CommandType = CommandType.StoredProcedure;
if (editData["oper"].ToString() == "del")
{
com.Parameters.AddWithValue("#UserID", editData["UserID"] == DBNull.Value ? 0 : editData["UserID"]);
com.Parameters.AddWithValue("#Actiontype", editData["oper"].ToString());
}
else
{
com.Parameters.AddWithValue("#UserID", editData["UserID"] == DBNull.Value ? 0 : editData["UserID"]);
com.Parameters.AddWithValue("#FirstName", editData["FirstName"].ToString());
com.Parameters.AddWithValue("#LastName", editData["LastName"].ToString());
com.Parameters.AddWithValue("#IsActive", editData["IsActive"].ToString());
com.Parameters.AddWithValue("#Department", editData["Department"].ToString());
com.Parameters.AddWithValue("#Email", editData["Email"].ToString());
com.Parameters.AddWithValue("#IsSuperAdmin", editData["IsSuperAdmin"].ToString());
com.Parameters.AddWithValue("#JobRole", editData["JobRole"].ToString());
com.Parameters.AddWithValue("#UserName", editData["UserName"].ToString());
}
com.Connection = conn;
conn.Open();
int m = com.ExecuteNonQuery();
if (m > 0)
{
if (editData["oper"].ToString() == "add")
{
returnValue = "Record Added Successfully";
}
else if (editData["oper"].ToString() == "edit")
{
returnValue = "Record Updated Successfully";
}
else if (editData["oper"].ToString() == "del")
{
returnValue = "Record Deleted Successfully";
}
else
{
throw new Exception("there is problem");
}
}
}
catch (Exception ex)
{
returnValue = ex.Message.ToString();
}
finally
{
conn.Close();
}
return returnValue;
}
//WebMethod
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string EditUpdateDelete(object data)
{
Helper.InsertUpdateDeleteBLL insertUpdateDelete = new Helper.InsertUpdateDeleteBLL();
string returnMessage = insertUpdateDelete.InsertUpdateDeleteMethod(data);
return returnMessage;
}
<script type="text/javascript">
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "MyTestPage.aspx/getData",
dataType: "json",
success: function (data) {
data = data.d;
$("#list").jqGrid({
datatype: "local",
colNames: ['UserID', 'First Name', 'Last Name', 'Is Active', 'Department', 'Email', 'Is Super Admin', "Job Role", 'Username'],
colModel: [
{ name: 'UserID', index: 'UserID', width: 50, stype: 'text' },
{ name: 'FirstName', index: 'FirstName', width: 130, stype: 'text', sortable: true, editable: true },
{ name: 'LastName', index: 'LastName', width: 130, editable: true },
{ name: 'IsActive', index: 'IsActive', width: 60, editable: false },
{ name: 'Department', index: 'Department', width: 80, align: "centre", sortable: true, editable: true },
{ name: 'Email', index: 'Email', width: 150, align: "centre", editable: true },
{ name: 'IsSuperAdmin', index: 'IsSuperAdmin', width: 150, align: "middle", editable: true },
{ name: 'JobRole', index: 'JobRole', width: 150, sortable: true, editable: true },
{ name: 'Username', index: 'Username', width: 100, sortable: true, editable: true }
],
data: JSON.parse(data),
rowno: 10,
loadonce: true,
multiselect: true,
rowlist: [5, 10, 20],
pager: '#pager',
viewrecords: true,
gridview: true,
sortorder: 'asc',
toppager: true,
editurl: 'MyTestPage.aspx/EditUpdateDelete',
cloneToTop: true,
async: false,
altrows: true,
autowidth: false,
hoverrows: true,
height: 200,
// rownumbers: true,
caption: "User Data"
});
$('#list').jqGrid('navGrid', '#pager',
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
cloneToTop: true
},
{
//update
recreateForm: true,
reloadAfterSubmit: false,
width: 500,
closeAfterEdit: true,
ajaxEditOptions: { contentType: "application/json" },
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
{
// add function
recreateForm: true,
beforeShowForm: function (form) {
$('#tr_UserID', form).hide();
},
width: 500,
reloadAfterSubmit: false,
closeAfterAdd: false,
ajaxEditOptions: { contentType: "application/json" },
//onclickSubmit: function (eparams) { alert('Hi');},
serializeEditData: function (postData) {
var postdata = { 'data': postData };
return JSON.stringify(postdata);
}
},
{
ajaxDelOptions: { contentType: "application/json" },
reloadAfterSubmit: false,
onclickSubmit: function (eparams) {
var retarr = {};
var sr = $("#list").getGridParam('selrow');
rowdata = $("#list").getRowData(sr);
retarr = { UserID: rowdata.UserID };
return retarr;
},
serializeDelData: function (data) {
var postData = { 'data': data };
return JSON.stringify(postData);
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
</script>

Jqgrid in asp.net MVC, one of the columns to be populated as drodpdown

I am using jqgrid in asp.net MVC5 with Entity Framework. For one of the columns I require it to be populated via database as a dropdown.
$("#grid").jqGrid({
colNames: ['Id', 'Date', 'PersonelID', 'OnCallType', 'Comments'],
colModel: [
{ key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
{ key: false, name: 'Date', index: 'Date', editable: true, formatter: 'date', formatoptions: { newformat: 'm/d/Y' }, sortable: true },
{ key: false, name: 'PersonelID', index: 'PersonelID', editable: true, edittype: 'select', editoptions: { dataUrl: '/Que/GetPersonnel' } },
{ key: false, name: 'OnCallType', index: 'OnCallType', editable: true, edittype: 'select', editoptions: { dataUrl: '/Que/GetCallType' } },
{ key: false, name: 'Comments', index: 'Comments', editable: true }, ]
});
what should i use in EditOptions to fetch value from database.
I tried using dataurl, but I couldnt get the code to work:-
public string GetPersonnel()
{
string final=string.Empty;
var query= new SelectList(db.PersonnelLocals.Where(o => o.QueLoc == true), "Index", "Text");
foreach (var item in query)
{
string newItem=item.Value.ToString()+":"+item.Text.ToString();
final = final + newItem + ",";
}
return final;
}
If there is any better method than using dataurl. Any help is greatly appreciated.

How to perform the search operation in server side in jQGrid using c#?

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

Categories