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

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

Related

Asp.Net MVC ajax sends empty object to Controller?

I am working on a survey application with Asp.Net MVC.
I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submit button, Submit form event (save or update) is fired. Asp.Net MVC ajax sends empty object to Controller. My Question object has Option list.So one-to-many relation.
Index.cshtml and submit(ajax) function
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru
Oluştur</a>
<table id="questionTable" class="table table-striped table-bordered accent-blue" style="width:
100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
QuestionController AddOrEdit action
[HttpPost]
public ActionResult AddOrEdit(Questions question)
{
using (MerinosSurveyEntities db = new MerinosSurveyEntities())
{
List<Options> options = (List<Options>) question.Options;
List<Options> existingOptions = new List<Options>(db.Options.Where(x => x.Status && x.IsActive && x.QuestionId == question.QuestionId));
foreach (Options existingOption in existingOptions)
{
Options optionUpdated = options.FirstOrDefault(x => x.OptionId == existingOption.OptionId);
if (optionUpdated != null)
{
//Update
existingOption.UpdatedDate = DateTime.Now;
existingOption.OptionName = optionUpdated.OptionName;
existingOption.IsActive = true;
existingOption.Status = true;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
options.RemoveAll(x => x.OptionId == existingOption.OptionId);
}
else
{
//Delete
existingOption.Status = false;
existingOption.UpdatedDate = DateTime.Now;
db.Options.Attach(existingOption);
db.Entry(existingOption).State = EntityState.Modified;
db.SaveChanges();
}
}
foreach (Options optionNew in existingOptions)
{
optionNew.IsActive = true;
optionNew.Status = true;
optionNew.CreatedDate = DateTime.Now;
optionNew.UpdatedDate = DateTime.Now;
db.Options.Add(optionNew);
db.SaveChanges();
return Json(new { success = true, message = "Soru ve seçenekleri başarılı şekilde oluşturuldu/güncellendi." }, JsonRequestBehavior.AllowGet);
}
// db.Questions.Attach(question);
return Json(new { success = true, message = "Soru başarılı bir şekilde güncellendi." }, JsonRequestBehavior.AllowGet);
}
}
Question object
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Questions
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Questions()
{
this.Responses = new HashSet<Responses>();
this.Options = new HashSet<Options>();
}
public int QuestionId { get; set; }
public string QuestionName { get; set; }
public int QuestionTypeId { get; set; }
public System.DateTime CreatedDate { get; set; }
public int CreatedUserId { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public System.DateTime UpdatedDate { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Responses> Responses { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Options> Options { get; set; }
}
}
Option class
//------------------------------------------------------------------------------
// <auto-generated>
//------------------------------------------------------------------------------
namespace MerinosSurvey.Models
{
using System;
using System.Collections.Generic;
public partial class Options
{
public int OptionId { get; set; }
public string OptionName { get; set; }
public int QuestionId { get; set; }
public System.DateTime CreatedDate { get; set; }
public System.DateTime UpdatedDate { get; set; }
public bool IsActive { get; set; }
public bool Status { get; set; }
public virtual Questions Questions { get; set; }
}
}
I finally solved the problem. Because I forgot to add 'contentType' to the section where I sent an ajax request, 'ajax' was sending empty objects to the controller. But both Pascal case and camel case I tried with the result has not changed. I've seen Ajax work independently in Case.
I'm adding the section I'm editing. In this case, it works without problems.
function SubmitForm(form) {
event.preventDefault();
if (form.checkValidity() === false) {
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
question.questionName = "Name";
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.optionId = row.find("TD").eq(0).html();
option.optionName = row.find("TD").eq(1).html();
option.questionId = 0;
option.isActive = true;
option.status = true;
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
contentType: "application/json",//this is the line I forgot to add.
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
//dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

Why highchart not show me in asp.net?

I'm beginner in asp.net and highchart control,want to use highchart control in my web application web form,for that purpose read this tutorial:
this tutorial
and write this web service in my project:
public class cityPopulation
{
public string city_name { get; set; }
public int population { get; set; }
public string id { get; set; }
}
[WebMethod]
public List<cityPopulation> getCityPopulation(List<string> pData)
{
List<cityPopulation> p = new List<cityPopulation>();
cityPopulation cpData = new cityPopulation();
cpData.city_name = "tabriz";
cpData.population = 100;
p.Add(cpData);
return p;
}
that web service name is this:
WebService1.asmx
and in my web form write this script :
<script type="text/javascript">
function drawPieChart(seriesData) {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'Population percentage city wise'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: "Brands",
colorByPoint: true,
data: seriesData
}]
});
}
$("#btnCreatePieChart").on('click', function (e) {
var pData = [];
pData[0] = $("#ddlyear").val();
var jsonData = JSON.stringify({ pData: pData });
$.ajax({
type: "POST",
url: "WebService1.asmx/getCityPopulation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(response) {
var aData = response.d;
var arr = []
$.map(aData, function (item, index) {
var i = [item.city_name, item.population];
var obj = {};
obj.name = item.city_name;
obj.y = item.population;
arr.push(obj);
});
var myJsonString = JSON.stringify(arr);
var jsonArray = JSON.parse(JSON.stringify(arr));
drawPieChart(jsonArray);
}
function OnErrorCall_(response) {
alert("Whoops something went wrong!");
}
e.preventDefault();
});
//*
</script>
before that script write this code:
<script src="Scripts/jquery-2.2.3.min.js"></script>
<script src="Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
and write this html code:
<select id="ddlyear">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
</select>
<button id="btnCreatePieChart">Show </button>
<br />
<div>
<div id="container" style="width: 500px; height: 500px"></div>
</div>
but when i run project and fire the button,can not see anything,and chart not show to me,what happen?is my code incorrect?how can i solve that problem?thanks.
i think ajax can not call the web service!

kendo ui gird server paging send pageSize failed with asp.net web API

I use below code to invoke web api to get the data, but how to send pagesize, skip to web api.
$scope.consulationWorklist = {
dataSource:
new kendo.data.DataSource({
schema: {
data: "consultationItems",
total: "count"
},
serverPaging: true,
transport: {
read: function (options) {
$.ajax({
url: "http://localhost:61274/api/v1/consultation/search/result",
dataType: "json",
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
}
},
pageSize: 2,
}),
pageable: {
refresh: true,
//pageSizes: true,
buttonCount: 5,
input: true
},
scrollable: true,
filterable: true,
sortable: true,
columnMenu: true,
resizable: true,
};
ASP.NET WEB API CODE:
[HttpGet]
[Route("search/result")]
public IHttpActionResult SimpleSearch(int pageSize, int skip)
{
IEnumerable<ConsultationItemDto> result = _ConsultationService.GetAllConsultationItem();
return Ok(new WorklistSearchResultDto
{
Count = result.Count(),
ConsultationItems = result
});
}
There are many discussion said that the kendo will send the pageSize and skip when setting the serverpaging to true. But not works. any one can help ?
As per my approach I used the parameter map attribute to stringify the parameters so i can accept one DTO on WebAPI:
transport: {
read: {
url: svcSampleUrl,
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
parameterMap: function (options) {
return kendo.stringify(options); //contains take, skip, sort, and filters
}
},
and accepted this DTO at server end:
public class SearchDTO
{
public int take { get; set; }
public int skip { get; set; }
public List<SortCriteria> sort { get; set; }
public List<FilterCriteria> filter { get; set; }
}
public class SortCriteria
{
public string field { get; set; }
public string dir { get; set; }
}
public class FilterCriteria
{
public string field { get; set; }
public string operator { get; set; }
public string value { get; set; }
}
my WebAPI method then looked like this:
[HttpPost]
[ActionName("GetItems")]
public SampleResponse GetItems(SearchDTO searchDTO)
{
//Calling a different layer for the read operation based in the parameter values
return BusinessLayer.GetItems(searchDTO);
}
Use url instead of read function,I resolved this issue.
$scope.consulationWorklist = {
dataSource:
new kendo.data.DataSource({
schema: {
data: "consultationItems",
total: "count"
},
serverPaging: true,
transport: {
read:
{
url: "http://localhost:61274/api/v1/consultation/search/result",
dataType: "json",
},
},
pageSize: 2,
}),
pageable: {
refresh: true,
buttonCount: 5,
input: true
},
scrollable: true,
filterable: true,
sortable: true,
resizable: true,
reorderable: 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")'

Not able to Add row using JQGrid

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

Resources