JQgrid is not working in MVC4 and EntityFramework - asp.net

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")'

Related

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!

How to hit JQGrid url in asp.net web form?

I am new in asp.net web form and i am unable to hit the url. Jqgrid is showing but the url to get data is not hitting. This is my aspx content named as emplosyee_list.aspx.
<%# Page Title="" Language="C#" MasterPageFile="~/main.Master" AutoEventWireup="true" CodeBehind="employee_list.aspx.cs" Inherits="CollegeManagementSystem.employee_list" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Content" runat="server">
<div id="page-wrapper">
Back
<div class="container-fluid">
<div class="col-lg-5">
<div>
<span class="headerFont">Employee List</span>
<hr class="lining"/>
</div>
</div>
</div>
</div>
<div >
<table id="grid">
</table>
</div>
<link href="../Content/Site.css" rel="stylesheet" />
<link href="../Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
<link href="../Content/StyleSheet1.css" rel="stylesheet" />
<script src="../Scripts/jquery-1.9.1.js"></script>
<script src="../Scripts/jquery-1.9.1.min.js"></script>
<script src="../Scripts/jquery.jqGrid.js"></script>
<script src="../Scripts/jquery.jqGrid.min.js"></script>
<script src="../Scripts/employeeJquery.js"></script>
</asp:Content>
This is my employee_list.aspx.cs
{
public partial class employee_list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string GetList()
{
var list = GetDataFromDB();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(list);
}
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog='College Management System';Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("SELECT username, name, DOB, date, gender,address,mobile,phone,email FROM employee_details ORDER BY username", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
}
}
And this is my Jqgrid code
$("#grid").jqGrid({
url: '/Admin/employee_list.aspx/GetList',
datatype: "json",
colNames: ['User', 'Name', 'DOB', 'Date',
'Gender', 'Address', "Mobile", 'Phone', 'Email', ],
colModel: [
{ name: 'User', index: 'User', width: 50, stype: 'text' },
{ name: 'Name', index: 'Name', width: 150 },
{ name: 'DOB', index: 'DOB', width: 100 },
{ name: 'Date', index: 'Date', width: 80, align: "right" },
{ name: 'Gender', index: 'Gender', width: 80, align: "right" },
{ name: 'Address', index: 'Address', width: 80, align: "right" },
{ name: 'Mobile', index: 'Mobile', width: 150, sortable: false },
{ name: 'Phone', index: 'Phone', width: 100, sortable: false },
{ name: 'Email', index: 'Email', width: 150, sortable: false }
],
pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] },
rowNum: 10,
rowList: [10, 20, 30],
sortname: 'id',
viewrecords: true,
pager :'#gridpager',
sortorder: "desc",
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete",
caption: "List Employee Details"
});
The url is not hiting and there is no error on consoleWhat is the problem
I see the following errors in your code:
you should include jQuery UI CSS on the HTML page. You can use for example <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css" rel="stylesheet" />
you can't include both minimized and non-minimized versions on the same page. So you should remove, for example, the references to non-minimized files jquery-1.9.1.js and jquery.jqGrid.js.
you should include the reference to i18n/grid.locale-en.js (or other locale file) before jquery.jqGrid.min.js.
You should remove from GetList() the line JavaScriptSerializer serializer = new JavaScriptSerializer(); and the call of serializer.Serialize. Instead of that the WebMethod should return object. The dot net framework will serialize the object to JSON or XML based on the contentType of HTTP request. The code of GetList method could look like
[WebMethod]
public object GetList()
{
return GetDataFromDB();
}
you should include in the option of jqGrid the following:
mtype: 'POST',
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
jsonReader: {
root: function (obj) {
// after the fix of WebMethod the next line
// can be reduced to
// return obj.d;
return typeof obj.d === "string" ? $.parseJSON(obj.d) : obj.d;
},
repeatitems: false
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
height: "auto",
gridview: true
Moreover the value of pager parameter seems be wrong. You don't wrote which version of jqGrid you use and which fork (). I don't know specific options of Guriddo jqGrid JS, but in case of usage free jqGrid or old jqGrid in version <= 4.7, the pager parameter have wrong value.
I recommend you to remove all index properties from colModel.

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

Binding database with kendo UI grid in ASP.NET MVC

I am trying to implement KendoUI Grid control in my ASP.NET MVC application.
I know KendoUI guys have given numerous examples but its not working for me.
My Model code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data;
namespace KendoGrid.Models
{
public class status
{
public string SiteId { get; set; }
public string SiteName { get; set; }
public string SiteStatus { get; set; }
public static List<status> StatusInfo()
{
SqlConnection sconn = new SqlConnection(#"Data Source=DS-7071BC8FDEE6\SQLEXPRESS;Initial Catalog=AmanoTest;User ID=sa;Password=india#123");
SqlCommand cmd = new SqlCommand("select * from SiteMaster", sconn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
status cstat;
List<status> statlist = new List<status>();
foreach (DataRow dr1 in dt.Rows)
{
cstat = new status();
cstat.SiteId = dr1[0].ToString();
cstat.SiteName = dr1[1].ToString();
cstat.SiteStatus = dr1[2].ToString();
statlist.Add(cstat);
}
return statlist;
}
}
}
My Controller Code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KendoGrid.Models;
using Kendo.Mvc.UI;
namespace KendoGrid.Controllers
{
public class statusController : Controller
{
//
// GET: /status/
public ActionResult Index()
{
return View();
}
public ActionResult Site()
{
//List<status> status = status.GetStatus();
List<status> temp = status.StatusInfo();
ViewData["table"] = temp;
return View();
}
}
}
And my view (.cshtml page) is:
#model KendoGrid.Models.status
#using Kendo.Mvc.UI
#*#{
Layout = null;
}
*#
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Site</title>
</head>
<body>
<div>
#(Html.Kendo().Grid(Model)()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
columns.Bound(p => p.siteID);
})
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
)
</div>
</body>
</html>
On executing it says :
The best overloaded method match for
'Kendo.Mvc.UI.Fluent.WidgetFactory.Grid(System.Data.DataTable)' has
some invalid arguments
Look like you are missing couple step here. Please go through this step n this might resolve your problem
http://docs.kendoui.com/getting-started/using-kendo-with/aspnet-mvc/helpers/grid/ajax-binding
You can use
var url = "/DesktopModules/MyServices/API/ATSManageClient/GetAllProjectsTechnologyBased?PortalId=210&tabid=95&Technology=" + selectedplatform;
var element = $("#grid").kendoGrid({
//debugger;
type: "odata",
dataSource: {
transport: {
read: url
},
schema: {
model: {
fields: {
RecievedDate: { type: "date" }
}
}
},
pageSize: 100
},
columnMenu: true,
scrollable: true,
filterable: true,
resizable: true,
sortable: true,
detailTemplate: kendo.template($("#template").html()),
detailInit: detailInit,
dataBound: function () {
},
columns: [
{
field: "ProjectID",
title: "Action",
template: "<a href='/Dashboard/Communication?ProjectID=#=ProjectID#'>View Communication</a>",
width: "20%"
},
//s debugger;
{
field: "ClientName",
width: "20%",
title: "Client",
template: "<a href='Accounts/UpdateClient.aspx?ClientId=#=ClientID#'> #= ClientName #</a>",
attributes: {
title: "#=ClientName#"
}
},
{
field: "ProjectTitle",
width: "20%",
title: "Project",
template: "<a href='Project/EditProject.aspx?ProjectID=#=ProjectID#'> #= ProjectTitle #</a>",
attributes: {
title: "#=ProjectTitle#"
}
},
{
field: "ColorList",
width: "20%",
template: kendo.template($("#template2").html()),
title: "Status"
},
{
field: "RecievedDate",
width: "20%",
title: "Check List Status",
template: ""
},
{
field: "RecievedDate",
width: "20%",
title: "Opened Bugs",
template: ""
}
],
pageable: {
// we don't set any DataSource here
pageSizes: [100, 150, 200]
}
});

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