asp.net-MVC Edit GridDate based on the role - asp.net-mvc-3

I've a datagrid to show employee particular but i need to set a logic where
if Role=Manager then show all the employee and if Role=Employee show only 1 data which belong to him. Below is my code to show the employee. I managed to show all employee. Need help to set filter for employee.
View
#model IEnumerable<SealManagementPortal_3._0.Models.VOC_CUSTODIAN>
#{
ViewBag.Title = "List of Custodians";
}
<h2>Index</h2>
<p>
#if (User.IsInRole("Manager"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list2").jqGrid({
url: '#Url.Action("GridData", "Custodian")',
datatype: 'json',
mtype: 'GET',
colNames: ['Agent ID', 'Branch', 'Unique ID', 'Custodian Name', /*'NRIC No', 'E-Mail', 'Contact No', 'Mobile No',*/'Role', 'Details', 'Edit', 'Delete'],
colModel: [
{ name: 'Agent ID', index: '', width: 10, align: 'left' },
{ name: 'Branch', index: '', width: 10, align: 'left' },
{ name: 'Unique ID', index: '', width: 10, align: 'left' },
{ name: 'Custodian Name', index: '', width: 10, align: 'left' },
{name: 'Role', index: '', width: 10, align: 'left' },
{ name: 'Details', index: '', width: 5, align: 'left' }
, { name: 'Edit', index: '', width: 5, align: 'left' }
,{ name: 'Delete', index: '', width: 5, align: 'left' }
],
pager: jQuery('#pager2'),
rowNum: 10,
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
autowidth: true,
caption: 'Custodians List'
});
});
</script>
#using (Html.BeginForm())
{
<table id="list2" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align:center;"></div>
}
Controller
public ActionResult GridData (string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.VOC_CUSTODIAN.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from custo in db.VOC_CUSTODIAN.AsEnumerable()
select new
{
id = custo.Idx,
cell = new string []
{
custo.StaffId,
custo.Branch,
custo.UniqueId,
custo.Name,
custo.Role,
("<a href='"+ #Url.Action("Details", "Custodian") +"/"+ custo.Idx+ "'>DETAILS</a>"),
("<a href='"+ #Url.Action("Edit", "Custodian") +"/"+ custo.Idx+ "'>EDIT</a>"),
("<a href='"+ #Url.Action("Delete", "Custodian") +"/"+ custo.Idx+ "'>DELETE</a>")
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}

Your view should not handle the logic, your Controller Action should. You should be able to do something like this with Roles.InUserInRole:
if (!Roles.IsUserInRole(User.Identity.Name, "Managers"))
{
jsonData.total = 1;
jsonData.page = 1;
jsonData.records = 1;
jsonData.rows = jsonData.rows.Where(x => x.id = currentUserId).ToArray()
}
return Json(jsonData, JsonRequestBehavior.AllowGet);

Related

Formatters give incorrect result after sort or search

I have following code using free-jqgrid. It loads correctly for the first time (Status is “Active” and Partner? is “Yes”). But when I do a sort or search, the values become incorrect(Status is “Retired” and Partner? is “No”).
Why the formatters are giving incorrect values? How to fix this?
SCRIPT
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/start/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/js/jquery.jqgrid.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.13.6/css/ui.jqgrid.min.css" rel="stylesheet" />
<script type="text/javascript">
function getCurrentPractice ()
{
return "Test";
}
function getGridCaption() {
return "<div style='font-size:15px; font-weight:bold; display:inline; padding-left:10px;'><span class='glyphicon glyphicon-check' style='margin-right:3px;font-size:14px;'></span>" + getCurrentPractice() + " " + "</div>" +
"<div style='float:right; padding-right:20px; padding-bottom:10px; display:inline;>" +
"<div style='float:right;width:550px; padding-bottom:20px;'>" +
"<input type='text' class='form-control' id='filter' placeholder='Search' style='width:250px; height:30px; float:right; ' />" +
" </div>" +
"</div>";
}
$(function () {
var currentPractice = "P";
var grid = $("#list2");
grid.jqGrid({
url: '/Home/GetProviders',
datatype: "json",
postData:
{
practiceName: function () { return currentPractice }
},
colNames: [
'Practice',
'ProviderID',
'Partner?',
'Status'
],
colModel: [
{ name: 'Practice', hidden: false },
{ name: 'ProviderID', hidden: false },
{
name: 'PartnerStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isPartner = rowObject.IsPartner;
return isPartner == true ? 'Yes' : 'No';
}
},
{
name: 'ActiveStatusText',
width: 70,
formatter: function (cellvalue, options, rowObject) {
var isActive = rowObject.IsActive;
return isActive == true ? 'Active' : 'Retired';
}
}
],
ignoreCase: true,
loadonce: true,
rowNum: 25,
rowList: [15, 25, 35, 50],
pager: '#pager2',
viewrecords: true,
sortable: true,
caption: getGridCaption(),
beforeSelectRow: function (rowid, e) {
//Avoid selection of row
return false;
},
loadComplete: function () {
}
});
grid.jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false });
//Filter Toolbar
$("#advancedSearch").click(function () {
grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: "cn" });
});
//Top Search
$("#filter").on('keyup', function () {
var searchFiler = $("#filter").val(), f;
if (searchFiler.length === 0) {
grid[0].p.search = false;
$.extend(grid[0].p.postData, { filters: "" });
}
f = { groupOp: "OR", rules: [] };
f.rules.push({ field: "Practice", op: "cn", data: searchFiler });
grid[0].p.search = true;
$.extend(grid[0].p.postData, { filters: JSON.stringify(f) });
grid.trigger("reloadGrid", [{ page: 1, current: true }]);
});
});
</script>
</head>
HTML
<div style="float:left; border:1px solid red;">
<div id="divGrid" style="width: 680px; min-height: 50px; float: left; border: 1px solid silver;">
<table id="list2"></table>
<div id="pager2"></div>
</div>
</div>
Server Code
[AllowAnonymous]
public JsonResult GetProviders(string practiceName)
{
//System.Threading.Thread.Sleep(3000);
List<Provider> providers = new List<Provider>();
Provider p = new Provider();
p.Practice = "Test1";
p.ProviderID = 1;
p.IsActive = true;
p.IsPartner = true;
providers.Add(p);
Provider p2 = new Provider();
p2.Practice = "Test2";
p2.ProviderID = 2;
p2.IsActive = true;
p2.IsPartner = true;
providers.Add(p2);
return Json(providers, JsonRequestBehavior.AllowGet);
}
UPDATE
Thanks to Oleg, working demo can be found here - Fiddle . It uses "/echo/json/" service of JSFiddle to get data from server.
It uses sorttype and additionalProperties. This can be rewritten without additionalProperties - I need to do it when I get a chance to revisit this.
The problem seems be very easy. The data returned from the server contains properties Practice, ProviderID, IsActive and IsPartner. The properties are available in rowObject during initial loading. You use additionally loadonce: true option. Thus free jqGrid will try to save some data locally, but which one? jqGrid saves by default the properties which corresponds the names of columns: Practice, ProviderID, PartnerStatusText and ActiveStatusText, but jqGrid have no information that other properties IsActive and IsPartner need be saved too.
You can solve the problem in two alternative ways:
you rename the column names PartnerStatusText and ActiveStatusText to IsActive and IsPartner.
you add the option additionalProperties: ["IsActive", "IsPartner"] to inform jqGrid to read and save locally additional properties.
Moreover, I'd recommend you to use options.rowData instead of rowObject inside of custom formatter. You can skip the 3-d parameter and to use formatter: function (cellvalue, options) {...}.
The final remark: the current code of the custom formatter is very easy. You need to replace some input values (true and false) to another text. One can use formatter: "select" for the case:
colModel: [
{ name: "Practice" },
{ name: "ProviderID" },
{
name: "IsPartner",
width: 70,
formatter: "select",
formatoptions: { value: "false:No;true:Yes" }
},
{
name: "IsActive",
width: 70,
formatter: "select",
formatoptions: { value: "false:Retired;true:Active" }
}
],
See https://jsfiddle.net/c9fge9yk/1/

MVC3 jqGrid subgrid using subGridrowExpanded

I'm developing an MVC3/razor application, and I am trying to use the subGridRowExpanded to nest a jqGrid inside another (so I can use the formatter amongst other things), how do i pass the id value Of the parent Grid to the Child grid?
The below code runs the main grid, and populates it with Data from the "Search/Customers" URL, but I do not know how to select the record I've Selected in the 'Search/BankLinks' URL controller
Can anyone tell me how to do this?
Thanks in advance
Andrew.
My Index.cshtml
#{
ViewBag.Title = "Index";
}
<h2>#ViewBag.Message</h2>
<div id="content">
<div id="content-left">
#Html.Partial("SearchPanel")
</div>
<div id="content-main">
<table id="jpgCustomers" cellpadding="0" cellspacing="0"></table>
<div id="jpgpCustomers" style="text-align:center;"></div>
</div>
</div>
#section JavaScript
{
<script type="text/javascript">
$(document).ready(function ()
{
$('#jpgCustomers').jqGrid({
//url from wich data should be requested
url: '#Url.Action("Customers")',
datatype: 'json',
mtype: 'POST',
colNames: ['Name', 'FullName', 'SFTP Enabled', 'IsTranbase'],
colModel: [
{ name: 'LogonName', index: 'LogonName', align: 'left' },
{ name: 'FullName', index: 'FullName', align: 'left' },
{ name: 'Enabled', index: 'Enabled', align: 'left' },
{ name: 'IsTran', index: 'IsTranbase', align: 'left' }
],
pager: $('#jpgpCustomers'),
rowNum: 10,
sortname: 'FullName',
sortorder: 'asc',
viewrecords: true,
height: '100%',
subGrid: true,
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id+"_t";
pager_id = "p_"+subgrid_table_id;
$("#"+subgrid_id).html("<table id='"+subgrid_table_id+"'class='scroll'></table><div id='"+pager_id+"'class='scroll'></div>");
$("#"+subgrid_table_id).jqGrid({
url: '#Url.Action("BankLinks")',
datatype: 'json',
mtype: 'POST',
colNames: ['Bank', 'Folder', 'Enabled'],
colModel:[
{name:"Bank",index:"Bank",width:80,key:true},
{name:"Folder",index:"Folder",width:130},
{name:"Enabled",index:"Enabled",width:70,align:"left"}
],
rowNum:20,
pager: pager_id,
sortname: 'Bank',
sortorder: "asc",
viewrecords: true,
height: '100%'
});
$("#"+subgrid_table_id).jqGrid('navGrid',"#"+pager_id,{edit:false,add:false,del:false})
},
});
});
</script>
}
My Controller Actions:
Customers
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Customers(JqGridRequest request)
{
ISession session = NHibernateHelper.GetCurrentSession();
IEnumerable<Customer> customers = session.QueryOver<Customer>().List().Skip<Customer>(0).Take<Customer>(request.RecordsCount);
int totalRecords = customers.Count();
//Prepare JqGridData instance
JqGridResponse response = new JqGridResponse()
{
//Total pages count
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
//Page number
PageIndex = request.PageIndex,
//Total records count
TotalRecordsCount = totalRecords
};
//Table with rows data
foreach (Customer customer in customers)
{
response.Records.Add(new JqGridRecord(Convert.ToString(customer.Id), new List<object>()
{
customer.FtpDetails.LogonName,
customer.FtpDetails.FullName,
customer.FtpDetails.Enabled,
customer.IsTran
}));
}
//Return data as json
return new JqGridJsonResult() { Data = response };
}
BankLinks
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BankLinks(JqGridRequest request)
{
ISession session = NHibernateHelper.GetCurrentSession();
//IN THIS LINE I HAVE HARDCODED value 14 - I need this value to be passed from the
//Parent Grid!
Customer customer = session.Get<Customer>(14);
int totalRecords = customer.Banks.Count();
//Prepare JqGridData instance
JqGridResponse response = new JqGridResponse()
{
//Total pages count
TotalPagesCount = (int)Math.Ceiling((float)totalRecords / (float)request.RecordsCount),
//Page number
PageIndex = request.PageIndex,
//Total records count
TotalRecordsCount = totalRecords
};
foreach (Bank bank in customer.Banks.ToList<Bank>())
{
CustomerBank bankLink = session.QueryOver<CustomerBank>().Where(x => x.BankId == bank.Id).Where(y => y.CustomerId == customer.Id).List<CustomerBank>().FirstOrDefault();
response.Records.Add(new JqGridRecord(null, new List<object>()
{
bank.BankCode,
bank.Folder,
bankLink.Enabled
}));
}
return new JqGridJsonResult() { Data = response };
}
First you should modify your subGridRowExpanded callback like this:
subGridRowExpanded: function(subgrid_id, row_id) {
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + '_t';
pager_id = "p_"+subgrid_table_id;
$('#' + subgrid_id).html('<table id="' + subgrid_table_id + '" class="scroll"></table><div id="' + pager_id + '" class="scroll"></div>');
$('#' + subgrid_table_id).jqGrid({
url: encodeURI('#Url.Action("BankLinks")' + '?id=' + row_id),
datatype: 'json',
mtype: 'POST',
colNames: ['Bank', 'Folder', 'Enabled'],
colModel: [
{name: 'Bank', index: 'Bank', width:80, key:true },
{name: 'Folder', index:'Folder', width:130 },
{name: 'Enabled', index: 'Enabled', width:70, align: 'left' }
],
rowNum: 20,
pager: pager_id,
sortname: 'Bank',
sortorder: 'asc',
viewrecords: true,
height: '100%'
});
$('#' + subgrid_table_id).jqGrid('navGrid', '#' + pager_id, {edit: false, add: false, del: false })
}
Notice the usage of encodeURI in order to make sure that the produced URL is valid.
Now you can modify your action method like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BankLinks(int id, JqGridRequest request)
{
//You can sue id parameter to get the data for selected client.
...
}
This should do the trick.

jqGrid: layout is broken?

i am using a jqgrid in a Dialog but it looks like the layout is broken:
Search button at bottom grid appears twice?
The font is too large.
When i display the grid as a normal view there are no issues.
index.cshtml to open the popup:
<div id="btnGo">
<img id="UserProfileLookUp" src="../../Content/images/ui-flag_blue.png" />
</div>
<script>
$(document).ready(function () {
$('#btnGo').click(function () {
$("#Dialog").dialog("open");
});
$("#Dialog").dialog({
modal: true,
autoOpen: false,
height: 413,
width: 626
});
});
</script>
<div id="Dialog" title="Product Select" style="display: none;">
#{Html.RenderAction("Test", "Home");}
</div>
the actual jqgrid:
<link href="#Url.Content("~/Content/site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/Content/jqGrid/jquery-ui-jqgrid.css")" rel="stylesheet" type="text/css" />
#{ ViewBag.Title = "jqGrid in ASP.NET MVC - Searching [Advanced]"; }
<table id="jqgProducts" cellpadding="0" cellspacing="0">
</table>
<div id="jqgpProducts" style="text-align: center;">
</div>
<div id="dlgSupplier">
</div>
<script id="tmplSupplier" type="text/x-jquery-tmpl">
${CompanyName}<br /><br />
${Address}<br />
${PostalCode}, ${City}<br />
${Country}<br /><br />
${Phone}<br />
${HomePage}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#jqgProducts').jqGrid({
//url from wich data should be requested
url: '#Url.Action("Products")',
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['ProductID', 'ProductName', 'Supplier', 'Category', 'QuantityPerUnit', 'UnitPrice', 'UnitsInStock'],
//columns model
colModel: [
{ name: 'ProductID', index: 'ProductID', align: 'left', search: true, stype: 'text', searchoptions: { sopt: ['eq', 'ne'] } },
{ name: 'ProductName', index: 'ProductName', align: 'left', search: true, stype: 'text', searchoptions: { sopt: ['eq', 'ne', 'bw', 'bn', 'ew', 'en', 'cn','nc']} },
{ name: 'Supplier', index: 'SupplierID', align: 'left', search: true, stype: 'select', searchoptions: { sopt: ['eq', 'ne'], dataUrl: '#Url.Action("Suppliers")' } },
{ name: 'Category', index: 'CategoryID', align: 'left', search: true, stype: 'select', searchoptions: { sopt: ['eq', 'ne'], dataUrl: '#Url.Action("Categories")' } },
{ name: 'QuantityPerUnit', index: 'QuantityPerUnit', align: 'left', search: false },
{ name: 'UnitPrice', index: 'UnitPrice', align: 'left', formatter: 'currency', formatoptions: { decimalSeparator: '.', thousandsSeparator: ',', decimalPlaces: 2, prefix: '$' }, search: false },
{ name: 'UnitsInStock', index: 'UnitsInStock', align: 'left', search: false }
],
//pager for grid
pager: $('#jqgpProducts'),
//number of rows per page
rowNum: 5,
//initial sorting column
sortname: 'ProductID',
//initial sorting direction
sortorder: 'asc',
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
$('#jqgProducts').jqGrid('navGrid', '#jqgpProducts', { edit: false, add: false, del: false, search: false }).jqGrid('navButtonAdd', '#jqgpProducts', {
caption: 'Search',
buttonicon: 'ui-icon-search',
onClickButton: function() {
$('#jqgProducts').jqGrid('searchGrid', { multipleSearch: true });
},
position: 'last',
title: 'Search'
});
$('#dlgSupplier').dialog({ autoOpen: false, bgiframe: true, resizable: false, title: 'Supplier' });
$('a[data-supplier-id]').live('click', function (e) {
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
var dialogPosition = $(this).offset();
$.post('#Url.Action("Edit")', { id: $(this).attr('data-supplier-id') }, function(data) {
});
});
});
</script>
controller:
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return PartialView();
}

How to make jqGrid row a link to an Action in asp.net MVC 3

I finally got my asp.net grid to display data...
But I need it to link to an action when clicking on one of the rows... or if need be, a single column How can I get a route into one of my columns or rows in MVC3?
I am using jqGrid btw...
Here is how I set up my Grid
$("#list").jqGrid({
shrinkToFit: false,
autowidth: true,
datatype: 'jsonstring',
mtype: 'POST',
colNames: [
'MRN',
'Hospital Fin',
'First Name',
'Last Name',
'Date of birth',
'Completed Pathway',
'Completed Pathway Reason',
'PCP Appointment',
'Specialist Appointment',
'Admit Date'
],
colModel: [
{ name: 'MRN', width: 125, align: 'left' },
{ name: 'Hospital_Fin', width: 145, align: 'left' },
{ name: 'First_Name', width: 115, align: 'left' },
{ name: 'Last_Name', width: 115, align: 'left' },
{ name: 'Date_of_birth', width: 145, align: 'left' },
{ name: 'Completed_Pathway', width: 125, align: 'left' },
{ name: 'Completed_Pathway_Reason', width: 165, align: 'left' },
{ name: 'PCP_Appointment', width: 115, align: 'left' },
{ name: 'Specialist_Appointment', width: 125, align: 'left' },
{ name: 'Admit_Date', width: 185, align: 'left' }],
rowNum: 10,
rowList: [5, 10, 20, 50],
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
imgpath: '/Content/themes/UPMC-theme/images',
caption: 'My first grid'
});
Any way to make an entire row clickable to an action method?
To open my view I need to call a controller and an action...
EditEncoutner is the controller, and EditEncounter is the Action...
public ActionResult EditEncounter(int encounterId, int popId)
{
string UID = HttpContext.User.Identity.Name;
DataRepository dr = new DataRepository();
PatientACOModel patMod = dr.Get(encounterId, UID);
TempData["POPULATIONID"] = popId;
return View(patMod);
}
Now I write up the JSON string myself... I am think of putting an <a /> tag in the relevant columns. But that would mean I am not making the entire row clickable, and I would then have to chose which column to put the link...
I could just make an edit column, which is what I will do if all else fails, I was kind of hoping for a more elegant solution however.
Assuming your View is binded to a List of Products class objects
#model IEnumerable<Product>
<table>
#foreach(var product in Model)
{
<tr class="trClickable" data-viewurl="#Url.Action("View","Product",new {#id=product.ID})">
<td>
#product.Name
</td>
<td>
#product.Price
</td>
</tr>
}
</table>
We will add a little javascript to capture the click event of the row.
<script type="text/javascript">
$(function () {
$(".trClickable").click(function () {
var item = $(this);
window.location.href = item.data("viewurl");
});
});
Assuming you have an action method called View inside your ProductController which accepts a parameter called id and show some data in it's view

Custom template column does not work in JQGrid

Experts,
I have JQGrid with custom template column like Edit. the following screen display data without Edit link in last column.
Javascript code:
<script language="javascript" type="text/javascript">
function editFmatter(cellvalue, options, rowObject) {
var cellHtml = "<a href='#' originalValue='" + cellvalue + "'>" + cellvalue + "</a>";
return cellHtml;
}
function unformatEdit(cellvalue, options) {
return $(cellObject.html()).attr("originalValue");
}
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("JQGridGetGridData", "TabMaster")',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name', 'Edit'],
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: 150, align: 'left', editable: true },
{ name: 'Edit', index: 'Edit', width: 80, align: "center", editable: true, formatter: editFmatter, unformat: unformatEdit }
],
pager: jQuery('#pager'),
rowNum: 100,
rowList: [10, 50, 100, 150],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '#Url.Content("~/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: '#Url.Action("JQGridEdit", "TabMaster")',
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record updated successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{
url: '#Url.Action("JQGridCreate", "TabMaster")',
closeAfterAdd: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record added successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Delete options
{
url: '#Url.Action("JQGridRemove", "TabMaster")',
afterSubmit: function (response, rowid) {
if (rowid.length > 0) {
jQuery("#success").show();
jQuery("#success").html("Record deleted successfully! [" + rowid + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
{
closeOnEscape: true,
multipleSearch: false,
closeAfterSearch: true
}
);
});
</script>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("Create New", "Create") | #Html.ActionLink("Bulk Insert", "AddList")
#* | #Html.ActionLink((string)ViewBag.RemoveSelectedTitle, "RemoveSelected")*#
</p>
<table id="list" class="scroll" cellpadding="0" cellspacing="0" width="100%">
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
<div id="success" style="color: Green">
</div>
Controller.cs
public JsonResult JQGridGetGridData(string sidx, string sord, int rows, int 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, "Edit" }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
First of all I would recommend you to take a look in this and this answers which shows how you can implement Edit links in the jqGrid.
Your current code have some problems:
In the unformatEdit you forgot to define the third parameter cellObject and use undefined value.
It's not good to add attributes like originalValue which are not corresponds to HTML standards. If you do need to extend attributes you should use data- prefix in the attribute name to be HTML5 compliant. In the case you can change the code to $(cellObject).children('a:first').attr("data-originalValue"); for example.
It is not good to define global functions because of possible name conflicts. You can move declaration of the function inside of jQuery(document).ready(function () {/*here*/}); event handler. You can define the function like a variables: var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/}; and use later in the same way like you did as before.
You should use the last version of jqGrid (currently 4.1.1). Many parameters like imgpath which you use are not exist since years (see here). If you look for more recent ASP.NET MVC code example I would recommend you take a look in the "UPDATED" part of the answer and download the corresponding code examples (the VS2008 project and the VS2010 project).
I have solved question from myself.
I have done following:
{ name: 'Edit', index: 'Edit', width: 80, align: 'center', editable: false, formatter: editFmatter, unformat: unformatEdit }
and
function editFmatter(el, cellval, opts) {
var editHTML = "<img src='Images/row_edit.gif' alt='Edit' title='Edit' onclick='openEditDialog(" + opts.rowId + ");'>";
var deleteHTML = "<img src='Images/row_delete.gif' alt='Delete' title='Delete' onclick='openDeleteDialog(" + opts.rowId + ");'>"; ;
var finalHTML = editHTML + " " + deleteHTML;
$(el).html(finalHTML);
}
function unformatEdit(cellvalue, options) {
//return $(el).html().attr("originalValue");
}
Thanks,
Imdadhusen

Resources