I want to create dynamic Jqgrid at runtime. I have made tow methods as
public ActionResult getdata( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
//return View(db.VideoModels.OrderByDescending(v => v.VideoId).ToPagedList(page, 3));
string[] columnNames = (string[])TempData["columnname"];
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (var dr in lst)
{
row = new Dictionary<string, object>();
rows.Add(row);
}
return Json(serializer.Serialize(lst), JsonRequestBehavior.AllowGet);
}
public ActionResult GetColumnDetails( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
var listOfStrings = new List<string>();
string[] colNames = listOfStrings.ToArray();
string[] columnNames = (from t in typeof(PrTblUsers).GetProperties() select t.Name).ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(colNames= columnNames), JsonRequestBehavior.AllowGet);
}
getcolumdetail is for getting column name and get data is for getting data.
div class="row">
<div id="content" style="margin-left:15px !important;">
<table id="datacopyProject"></table>
<div id="datacopy_pagerProject"></div>
#*<table id="datacopyfilter"></table>
<div id="datacopy_pagerfilter"></div>*#
</div>
</div>
<script type="text/javascript" id="getdata">
$(document).ready(function () {
var item = [];
//creating the dyanamic colmodel
$("#datacopyProject").jqGrid('GridUnload');
$.ajax(
{
type: "POST",
url: '/Test/GetColumnDetails',
//data: { tid: data },
dataType: "json",
success: function (result) {
var colModels = BuildColumnModel(JSON.parse(result));
//console.log(JSON.stringify(result));
//var obj = jQuery.parseJSON(result);
//var columnData = result.mypage,
item= getData();
//alert(item);
jQuery("#datacopyProject").jqGrid({
colNames: item,
colModel: colModels,
autowidth:true,
caption: "User List",
pager: jQuery('#datacopy_pagerProject'),
rowNum: 3,
viewrecords: true,
rowList: [5, 10, 20, 50],
viewrecords: true,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return $("#datacopyProject").jqGrid('getGridParam', 'page'); },
total: function (obj) { return Math.ceil(obj.length / $("#datacopyProject").jqGrid('getGridParam', 'rowNum')); },
records: function (obj) { return obj.length; }
},
gridComplete: function () {
},
loadComplete: function (data) { }
})
},
loadonce:true,
error: function (x, e) {
alert(x.readyState + " " + x.status + " " + e.msg);
}
});
//setTimeout(function () { $("#datacopyProject").jqGrid('setGridParam', { datatype: 'json' }); }, 500);
//binding the data to dyanamic colmodel
function getData()
{
$.ajax({
url: '/Test/getdata',
type: "POST",
datatype: "json",
//data: { userid: data },
async: false,
success: function (response) {
var resultData = JSON.parse(response);
//var data = resultData.slice(1, resultData.length - 1);
//var json = JSON.stringify(data);
//console.log(resultData);
////var resultData = JSON.parse(response);
for (var i = 0; i <= resultData.length; i++)
item = $("#datacopyProject").jqGrid('addRowData', i + 1, datacopyProject[i]);
//$(resultData).each(function (e) {
// $("#datacopyProject").addRowData(e, this);
//});
}
});
}
});
function BuildColumnModel(result) {
debugger;
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if (uFields[i].length > -1) {
columns.push({ name: uFields[i], index: uFields[i] })
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
I am getting the column value in jQgrid but not getting the rows.
You can use the solution explained in this post, and return from the controller a ViewBag with these variables joined:
var jsonGrid = jQuery.parseJSON('#Html.Raw(ViewBag.YourGridVariableInJson)');
Related
I have problem with passing data to select2 (ajax dynamic search) in edit mode on document ready.
I create test button which should add data on click and it doesnt work... Any ideas with that?
$('.select2').select2({
minimumInputLength: 3,
ajax: {
url: (...),
dataType: 'json',
data: function (params) {
return {
query: params.term
};
},
processResults: function (data, params) {
var resData = [];
data.forEach(function (value) {
if (value.name.toLowerCase().indexOf(params.term.toLowerCase()) != -1)
resData.push(value)
})
return {
results: $.map(resData, function (item) {
return {
text: item.name,
slug: item.slug,
id: item.id
}
})
};
},
},
});
$('#preselectObjectDataButton').on('click', function() {
var _array = []
var o = new Object;
o.id = 1;
o.text = "test";
o.slug = "test";
_array.push(o);
$('.select2').val(_array).trigger('change.select2');
});
I'm having trouble either understanding or implementing search/filter functionality in jqgrid.
The data set is returned to the client with each item having a list of designers:
"IAConsultWorkflowRequestsList": [
{
"AppID": "ISP",
"SubmittedDate": "12/13/2018",
"IAAssigned": "<a style='color:blue !important;' href='mailto:Joseph#somewhere.com'><u>Joseph Kraft</u></a>",
"IAAssignedName": null,
"Status": "In Discovery",
"SLA": 0,
"DaysPassed": 157,
"IsUserFM": false,
"IsUserSecureEnv": false,
"DesignParticipants": [
{
"Name": "John Kraft",
"EmailAddress": "",
"ID": "A2049"
},
{
"Name": "Zack Adamas",
"EmailAddress": "Zachary.Adamas#somewhere.com",
"ID": "U6696"
},
{
"Name": "David Kosov",
"EmailAddress": "David.Kosov#somewhere.com",
"ID": "U6644"
}
]
}
So in the 'Designers' column, I am concatenating the results to be comma separated, e.g.
John Kraft,
Zack Adamas,
David Kosov
And, if the item has an email address, the individual name is formatted as an email link:
<td role="gridcell" style="text-align:center;" title="John Kraft,Zack Burns,David Cosand" aria-describedby="workFlowIAGrid_DesignParticipants">
John Kraft,<br>
<a style="color:blue !important;" ref="mailto:Zachary#somewhere.com"><u>Zack </u></a>,<br>
<a style="color:blue !important;" href="mailto:David#somewhere.com"><u>David </u></a></td>
I have a select element with entries John, Zack, and David, but when I select one of the options, I do not get expected results. If I select David, I would like to be shown any rows that contain David as one of potentially several names in the Designer column.
However, I am getting erratic behavior. Some of the sopt options will cause something to happen, but not what is expected. None of the contains/not contained or in/not in options seem to do what I need. What am I doing wrong?
Per Tony's comment, here is the grid init code:
$gridEl.jqGrid({
xhrFields: {
cors: false
},
url: "/IAConsult/GetWorkFlowIARequests",
postData: {
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
datatype: "json",
crossDomain: true,
loadonce: true,
mtype: 'GET',
sortable: true,
viewrecords: true,
pager: '#workFlowIAGridPager',
multiselect: true,
rowNum: 50,
autowidth: true,
colModel: [
{ label: 'Design Participants', name: 'DesignParticipants', align: "center", formatter:commaSeparatedList },
//same for other columns...
],
beforeSelectRow: function (rowid, e) {
var $myGrid = $(this),
i = $.jgrid.getCellIndex($(e.target).closest('td')[0]),
cm = $myGrid.jqGrid('getGridParam', 'colModel');
return (cm[i].name === 'cb');
},
jsonReader: {
repeatitems: true,
root: "IAConsultWorkflowRequestsList"
},
beforeSubmitCell: function (rowid, name, value, iRow, iCol) {
return {
gridData: gridData
};
},
serializeCellData: function (postdata) {
return JSON.stringify(postdata);
},
gridComplete: function () {
rowCount = $gridEl.getGridParam('records');
gridViewRowCount = rowCount;
var rowIDs = $gridEl.getDataIDs();
var inCompleteFlag = false;
//Filter code to apply filter in headers in MyWork grid
var datatoFilter = $gridEl.jqGrid('getGridParam', 'lastSelectedData').length == 0
? $gridEl.jqGrid("getGridParam", "data")
: $gridEl.jqGrid('getGridParam', 'lastSelectedData');
var $grid = $gridEl, postfilt = "";
var getUniqueNames = function (columnName) {
var uniqueTexts = [],
mydata = datatoFilter,
texts = $.map(mydata, function(item) {
return item[columnName];
}),
textsLength = texts.length,
text = "",
textsMap = {},
i;
if (texts[0] && texts[0].Name)
texts = $.map(texts,
function(item) {
return item.Name;
});
for (i = 0; i < textsLength; i++) {
text = texts[i];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
if (columnName == 'ConsultID') {
return (uniqueTexts.sort(function (a, b) { return a - b; }));
} else return uniqueTexts.sort();
}, buildSearchSelect = function (uniqueNames) {
var values = {};
values[''] = 'All';
$.each(uniqueNames,
function () {
values[this] = this;
});
return values;
}, setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{
type: "change",
fn: function (e) {
setTimeout(function () {
//get values of dropdowns
var DesignParticipant = $('#gs_workFlowIAGrid_DesignParticipants').val();
//same for other columns...
var columnNamesArr = columns.split(',');
changedColumns.push(columnName);
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
var val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
$('#gs_workFlowIAGrid_DesignParticipants').val(DesignParticipant);
//same for other columns...
},
500);
//setting the values :
}
}
]
}
});
};
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
setSearchSelect.call($grid, "DesignParticipants");
//same for other columns...
$grid.jqGrid("filterToolbar",
{ stringResult: true, searchOnEnter: true });
var localFilter = $gridEl.jqGrid('getGridParam', 'postData').filters;
if (localFilter !== "" && localFilter != undefined) {
globalFilter = localFilter;
}
$gridEl.jqGrid("setGridParam",
{
postData: {
"filters": globalFilter,
showAll: showAllVal,
role: role,
IsIAArchitect: userIsIA
},
search: true,
forceClientSorting: true
})
.trigger("reloadGrid");
//Ending Filter code
var columnNamesArr = columns.split(',');
for (i = 0; i < columnNamesArr.length; i++) {
if (true) {
var htmlForSelect = '<option value="">All</option>';
var un = getUniqueNames(columnNamesArr[i]);
var $select = $("select[id='gs_workFlowIAGrid_" + columnNamesArr[i] + "']");
for (j = 0; j < un.length; j++) {
val = un[j];
htmlForSelect += '<option value="' + val + '">' + val + '</option>';
}
$select.find('option').remove().end().append(htmlForSelect);
}
}
},
// all grid parameters and additionally the following
loadComplete: function () {
$gridEl.jqGrid('setGridWidth', $(window).width(), true);
$gridEl.setGridWidth(window.innerWidth - 20);
},
height: '100%'
});
Here is the formatter I am using on the column:
function commaSeparatedList(cellValue, options, rowdata, action) {
let dps = [];
_.forEach(cellValue, function (item) {
let formatted = '';
if (item.EmailAddress)
formatted += '<a style="color:blue !important;" href="mailto:' +
item.EmailAddress +
'"><u>' +
item.Name +
'</u></a>';
else formatted = item.Name;
dps.push(formatted + ',<br/>');
});
let toString = dps.join('');
return toString.substring(0,toString.length-6);
}
And then the only other pertinent thing is that I used a function to return 'in' (or some other key - these are the options I said weren't apparently working in the initial post) if the column is named 'Design Participants', else equal for any other column:
setSearchSelect = function (columnName) {
var changedColumns = [];
this.jqGrid("setColProp",
columnName,
{
stype: "select",
searchoptions: {
value: buildSearchSelect(getUniqueNames.call(this, columnName)),
sopt: getSortOptionsByColName(columnName),
dataEvents: [
{...
function getSortOptionsByColName(colName) {
console.log(colName);
if (colName === 'DesignParticipants')
return ['in'];
else
return ['eq'];
}
The issue was that the underlying data (the DesignParticipants in the returned JSON above) did not match the selected string, since the data itself was an array. I believed the filtering was based on the displayed text in the grid table, but, it was based on the underlying data. So, I created a new property of the returned JSON that was a string, and the filtering worked as expected.
I have a kendo Treeview which is showing the parent nodes but the child nodes are not seen. Can anyone tell me where am i going wrong. I am new to this concept. I followed the below link but its not working.
http://demos.telerik.com/kendo-ui/treeview/remote-data-binding
function treeView() {
var treeM = new kendo.data.HierarchicalDataSource({
schema: {
data: function (response) {
console.log("response" + JSON.stringify(response));
var rdata = {};
if (response.d) {
rdata = JSON.parse(response.d);
}
else {
rdata = response;
}
return rdata; // ASMX services return JSON in the following format { "d": <result> }.
},
model: {
hasChildren: true,
id: "ID",
expanded: true,
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
},
},
transport: {
read: {
url: "/getParent",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json"
},
parameterMap: function (data, type) {
if ((type == "update") || (type == "create") || (type == "destroy")) {
console.log('parameterMap:');
return JSON.stringify({ "LinksJson": data });
console.log(JSON.stringify(data));
} else {
return data;
}
}
}
});
$("#treeview1").kendoTreeView({
dataSource: treeM,
dataValueField: "ID",
dataTextField: ["LINK","Name"]
});
}
$("#treeview").on("click", ".k-in", function (e) {
var tree = $("#treeview").data('kendoTreeView');
tree.toggle($(e.target).closest(".k-item"));
});
$(document).ready(function () {
treeView();
});
Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getParent()
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in context.Links
where x.ParentID == 68
select x;
var newQry = dataQuery.AsEnumerable().Select(c => new
{
ID = c.ID,
Name = c.Name,
Children = HasChildren(231)
});
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(newQry);
}
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool HasChildren(int ID)
{
using (var context = new Data.Entities())
{
IQueryable<ERPv2.Data.Links> dataQuery = from x in contextLinks
where x.ParentID == ID
select x;
return dataQuery.AsEnumerable().Any();
}
}
Even when you try to view the child nodes, it will try to call getLinks and not the getreports.
From what i have seen , you should have only one method for getting parent and children. Can be an array inside each parent node.
Can you combine the data from GetReports method inside getlinks itsself and give it a shot.
You should try and get this working here with hardcoded values and then do configure with services.
http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#configuration-dataSource
I want to create jqgrid by passing value from Datatable as I have multiple tables ,based on that I need to change colomn names dynamically,in asp.net mvc.
Hi after working hard on it finally i have got a solution.
<table id="tableDetails1" cellpadding="0" cellspacing="0">
<tr><td></td></tr></table>
<div id="pager" style="text-align: center"></div>
Jqgrid and javascript function
<script type="text/javascript">
$(document).ready(function () {
// $("#tableDetails1").GridUnload();
CreateColumnDetails();
});
function getData() {
debugger;
$.ajax({
url: '#Url.Action("TableDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
var obj = $.parseJSON(result);
resultData = JSON.parse(result);
$(resultData).each(function (e) {
$("#tableDetails1").addRowData(e, this);
});
}
});
}
function CreateColumnDetails() {
debugger;
$.ajax({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
var colName = JSON.parse(result);
debugger;
var colModels = BuildColumnModel(colName);
$("#tableDetails1").jqGrid({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
datatype: 'json',
colNames: colName,
colModel: colModels
})
}
});
getData();
}
function CreateGrid(result) {
debugger;
$("#tableDetails1").jqGrid({
url: '#Url.Action("TableDetails", "TableInfo")',
datatype: 'json',
mtype: 'Get',
pager: $('#pager'),
rowNum: 5,
gridview: true,
rowList: [5, 10, 20, 30],
height: '100%',
viewrecords: true,
caption: 'Table Details ',
emptyrecords: 'No Records found',
jsonReader: {
root: function (rows) {
debugger;
return typeof rows === "string" ? $.parseJSON(rows) : rows;
},
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
id: "0"
},
autowidth: true,
multiselect: false,
loadError: function (jqXHR, textStatus, errorThrown) {
debugger;
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
}).navGrid('pager', { edit: false, add: false, del: false });
}
function BuildColumnModel(result) {
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if(uFields[i].length>-1){
columns.push({ name: uFields[i], index: uFields[i]})
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
</script>
Controllers
**Httppost method adding rows dynamically
[HttpPost]
public ActionResult TableDetails(int? id, DataTable dt)
{
dt = new DataTable();
dt = GetTableDetails(id);
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)
{
serializer.Serialize(col.ColumnName);
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Json(serializer.Serialize(rows), JsonRequestBehavior.AllowGet);
}
Column Details in string format
[HttpPost]
public ActionResult GetColumnDetails(int ? id, DataTable dt)
{
dt = GetTableDetails(1);
// id = (int)Session["id"] ;
// dt = GetTableDetails(id);
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(columnNames), JsonRequestBehavior.AllowGet);
}
I was using MVC3 with AJAX. I was using AJAX within another AJAX. For the first AJAX request, it properly sends to the controller with data. But after returning from the AJAX request, I again posting the same data to another action. But second time the data comes null when coming to the controller. Please help me to fix this issue.
Code
$(document).ready(function () {
$('.deleteitems').live('click', function (e) {
var items = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items.push($(this).attr("Id"));
});
var json = JSON.stringify(items);
var perm = $("#Permission").val();
if (items.length != 0) {
if (perm == "True") {
$.ajax({
url: '/ItemControl/ItemControl/Catalogue_Check',
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data == "S") {
DelBibsAlso();
}
else {
DelItemsonly();
}
}
});
}
else {
$("#divMes").removeClass("Success");
$("#divMes").addClass("Error");
showError("Sorry you dont have Permission!");
}
}
else {
alert("Select any Items to delete");
e.preventDefault();
}
});
});
function DelItemsonly() {
var items2 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items2.push($(this).attr("Id"));
});
var itemjson = JSON.stringify(items2);
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": itemjson, "DelBib": 0 },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
function DelBibsAlso() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
var bibjson = JSON.stringify(items1);
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: { "id": bibjson, "DelBib": cond },
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});
}
else {
e.preventDefault();
}
}
Controller Code
public ActionResult Catalogue_Check(string[] id)
{
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
var Matched_BibID = (from asd in Db.Items
where ints.Contains(asd.Id)
select asd.BibId).ToList();
foreach (var idd in ints)
{
var bibid = (from bib in Db.Items where bib.Id == idd select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
return Json("S", JsonRequestBehavior.AllowGet);
}
}
return Json("N", JsonRequestBehavior.AllowGet);
}
public JsonResult DeleteItems(string[] id, int? DelBib)
{
//var newid = id.Split(',');
DeleteItem weed = new DeleteItem();
int[] ints = id.Select(x => int.Parse(x)).ToArray();
foreach (var a in id)
{
int sel = Convert.ToInt32(a);
Item item = Db.Items.Single(i => i.Id == sel);
int Sess = Convert.ToInt16(Session["AccId"]);
string AdminName = User.Identity.Name;
bool Exist = Db.RouteOuts.Any(itm => itm.ItemId == item.Id);
if (!Exist)
{
weed.DeleteIt(item, Sess, AdminName);
var bibid = (from bib in Db.Items where bib.Id == item.Id select bib.BibId).Single();
var checkbib = (from bibchk in Db.Items where bibchk.BibId == bibid && !ints.Contains(bibchk.Id) select bibchk.Id).Count();
if (checkbib == 0)
{
Db.ExecuteStoreCommand("update Bibs set Status= 'D' where Id={0}", item.BibId);
Db.SaveChanges();
}
}
}
return Json("S", JsonRequestBehavior.AllowGet);
}
function Test() {
var items1 = [];
$('.checkall').each(function () {
if ($(this).is(':checked'))
items1.push($(this).attr("Id"));
});
//var bibjson = JSON.stringify(items1); **** Loose this line ****
var value = confirm("Do you also want to delete the catalogue record?");
var cond = 0;
if (value) {
var cond = 1;
}
else {
cond = 0;
}
var val = confirm("Are you sure you want to delete these records?");
if (val) {
$.ajax({
url: '/ItemControl/ItemControl/DeleteItems',
type: 'POST',
dataType: 'json',
data: JSON.stringify({ "id": items1, "DelBib": cond }), // **** Items are stringified before posting ****
contentType: 'application/json; charset=utf-8',
success: function (data) {
e.preventDefault();
$(".t-grid .t-refresh").trigger('click');
$("#divMes").removeClass("Error");
$("#divMes").addClass("Success");
showError("Data Successfully Deleted");
}
});enter code here
}
else {
e.preventDefault();
}