فعال سازی و پردازش صفحات پویای افزودن، ویرایش و حذف رکوردهای jqGrid در ASP.NET MVC
نویسنده: وحید نصیری
تاریخ: ۱۳۹۳/۰۴/۱۴ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
colModel: [
{
// سایر ستونها
name: 'myac', width: 80, fixed: true, sortable: false,
resize: false, formatter: 'actions',
formatoptions: {
keys: true
}
}
],
colModel: [
{
name: 'Id', index: 'Id', align: 'right', width: 70,
editable: false
},
{
name: 'Name', index: 'Name', align: 'right', width: 100,
editable: true, edittype: 'text',
editoptions: {
maxlength: 40
},
editrules: {
required: true
}
},
{
name: 'Supplier.Id', index: 'Supplier.Id', align: 'right', width: 110,
editable: true, edittype: 'select',
editoptions: {
dataUrl: '@Url.Action("SuppliersSelect","Home")'
},
editrules: {
required: true
}
},
{
name: 'Category.Id', index: 'Category.Id', align: 'right', width: 110,
editable: true, edittype: 'select',
editoptions: {
dataUrl: '@Url.Action("CategoriesSelect","Home")'
},
editrules: {
required: true
}
},
{
name: 'Price', index: 'Price', align: 'center', width: 100,
formatter: 'currency',
formatoptions:
{
decimalSeparator: '.',
thousandsSeparator: ',',
decimalPlaces: 2,
prefix: '$'
},
editable: true, edittype: 'text',
editrules: {
required: true,
number: true,
minValue: 0
}
},
{
name: 'myac', width: 80, fixed: true, sortable: false,
resize: false, formatter: 'actions',
formatoptions: {
keys: true
}
}
], public ActionResult SuppliersSelect()
{
var list = ProductDataSource.LatestProducts;
var suppliers = list.Select(x => new SelectListItem
{
Text = x.Supplier.CompanyName,
Value = x.Supplier.Id.ToString(CultureInfo.InvariantCulture)
}).ToList();
return PartialView("_SelectPartial", suppliers);
} @model IList<SelectListItem>
@Html.DropDownList("srch", Model) $('#list').jqGrid({
caption: "آزمایش چهارم",
//url from wich data should be requested
url: '@Url.Action("GetProducts","Home")',
//url for edit operation
editurl: '@Url.Action("EditProduct","Home")', [HttpPost]
public ActionResult EditProduct(Product postData)
{
//todo: Edit product based on postData
return Json(true);
} $('#list').navGrid(
'#pager',
//enabling buttons
{ add: true, del: true, edit: false, search: false },
//edit options
{},
//add options
{ width: 'auto', url: '@Url.Action("AddProduct","Home")' },
//delete options
{ url: '@Url.Action("DeleteProduct","Home")' }
); [HttpPost]
public ActionResult DeleteProduct(string id)
{
//todo: Delete product
return Json(true);
}
[HttpPost]
public ActionResult AddProduct(Product postData)
{
//todo: Add product to repository
return Json(true);
} var lastSel;
function inlineEdit() {
$('input[name=rdEditApproach]').attr('disabled', true);
$('#list').navGrid(
'#pager',
//enabling buttons
{ add: true, del: true, edit: false, search: false },
//edit options
{},
//add options
{ width: 'auto', url: '@Url.Action("AddProduct","Home")' },
//delete options
{ url: '@Url.Action("DeleteProduct","Home")' }
);
//add onSelectRow event to support inline edit
$('#list').setGridParam({
onSelectRow: function (id) {
if (id && id != lastSel) {
//save changes in row
$('#list').saveRow(lastSel, false);
lastSel = id;
}
//trigger inline edit for row
$('#list').editRow(id, true);
}
});
}; function formEdit() {
$('input[name=rdEditApproach]').attr('disabled', true);
$('#list').navGrid(
'#pager',
//enabling buttons
{ add: true, del: true, edit: true, search: false },
//edit option
{
width: 'auto', checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#list'));
}
},
//add options
{
width: 'auto', url: '@Url.Action("AddProduct","Home")',
reloadAfterSubmit: false, checkOnUpdate: true, checkOnSubmit: true,
beforeShowForm: function (form) {
centerDialog(form, $('#list'));
}
},
//delete options
{
url: '@Url.Action("DeleteProduct","Home")', reloadAfterSubmit: false
})
.jqGrid('navButtonAdd', "#pager", {
caption: "حذف ردیفهای انتخابی", title: "Delete Toolbar", buttonicon: 'ui-icon ui-icon-trash',
onClickButton: function () {
var idsList = jQuery("#list").jqGrid('getGridParam', 'selarrrow');
alert(idsList);
//jQuery("#list").jqGrid('delGridRow',idsList,{reloadAfterSubmit:false});
}
});
};
function centerDialog(form, grid) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round( parentTop + (parentHeight-dlgHeight)/2 ) + "px";
dlgDiv[0].style.left = Math.round( parentLeft + (parentWidth-dlgWidth )/2 ) + "px";
}
3. Can be used in proprietary works The license policy allow you to use this piece of code even inside commercial (not open source) projects. So you can use this software without giving away your own (precious?) source code.
[HttpGet]
public string SelectAllJqTree()
{
var result = _kpiTypeService.SelectAll().Select(e => new
{
value = e.Id,
text = e.Name,
});
var select = "<select>{0}</select>";
var option = "<option value='{0}' >{1}</option>";
var options = "";
foreach (var item in result)
{
options += string.Format(option, item.value, item.text);
}
return string.Format(select, options).Trim();
} colModel: [
{
name: 'KpiTypeID', index: 'KpiTypeID', align: 'right', width: 300,
editable: true, edittype: 'select',
editoptions: {
dataUrl: '/api/KPIType/SelectAllJqTree'
},
editrules: {
required: true
}
}
] $.ajax({
url: "/api/KPIType/SelectAllJqTree",
context: document.body
}).done(function (data) {
$("#selection").html(data);
}); editoptions: { dataUrl: '...url to get json....',
buildSelect: function (response) {
var data = typeof response === "string" ? $.parseJSON(response.responseText) : response,
var s = "<select>";
s += '<option value="0">--No Manager--</option>';
$.each(data, function () {
s += '<option value="' + this.EmployeeId + '">' + this.EmployeeName + '</option>';
});
return s + "</select>";
}
} [HttpGet]
public IHttpActionResult SelectAllFake()
{
var result = new List<KpiTypeView>
{
new KpiTypeView() {KpiTypeID = 1, KpiTypeName = "افزایشی"},
new KpiTypeView() {KpiTypeID = 2, KpiTypeName = "کاهشی"}
};
return Json(result);
} configuration.Formatters.Clear(); configuration.Formatters.Add(new JsonMediaTypeFormatter());
$(document).ready(function () {
var securityToken = $('[name=__RequestVerificationToken]').val();
$('body').bind('ajaxSend', function (elm, xhr, s) {
if (s.type == 'POST' && typeof securityToken != 'undefined') {
if (s.data.length > 0) {
s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
else {
s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
}
}
});
});
onClickButton: function (e) {
var id = $('#grid').jqGrid('getGridParam', 'selrow');
if (id != null) {
var idHtml = $('#grid').jqGrid('getCell', id, 'ID_Baker');
//var idHtml = id.ID_Baker;
//var idHtml = $('#' + id).children().first().html();
$.ajax({
url: '@(Url.Action("DeleteProfile"))' + '?Id=' + idHtml + '&RowId=' + id,
success: function (data) {
if (data.Success) {
$('#grid').jqGrid('delRowData', data.RowId);
}
}
});
}
else {
}
},
$("#JQGrid1").jqGrid({
url: "/manager/Products/OnProductDataRequested",
editurl: '/manager/Products/EditProductData',
mtype: "GET",
datatype: "json",
page: 1,
sortname: 'Priority',
sortorder: "desc",
viewrecords: true,
jsonReader: { id: "Id" },
prmNames: { id: "Id" },
colNames: ["Id","خلاصه","توضیح خلاصه","قیمت","قیمت با تخفیف","درصد کارمزد سایت","آستانه هشدار موجودی","محتوا", "عنوان","فروشگاه","گروه","تعداد موجودی", "اولویت","محصولات مکمل","تصاویر","مقادیر مشخصه محصول","قیمت","نظرات", "فعال","ویژه","موجود","برند","عملیات درجا","عملیات کامل"],
colModel: [
{ key: true, width: 50, name: "Id", hidden: true, search: false },
{
editable: true, width: 10, name: "Abstract", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "AbstractDescription", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "Value", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "Discount", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "SiteWagePercentage", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "InventoryAlertLimit", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 10, name: "Context", search: true, stype: "text", editable: true,
hidden: true,
editrules: { edithidden: true }
},
{
editable: true, width: 150, name: "Title", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
name: "shopTitle", align: 'center', viewable: true, editrules: { edithidden: true },
search: true,
editable: true, stype: 'select',
edittype: 'select',
searchoptions: {
sopt: ["eq", "ne"],
dataUrl: "/manager/Products/Getshop/", buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.shId + '">' + this.shTitle + '</option>';
});
}
return s + '</select>';
},
},
editoptions: {
dataUrl: "/manager/Products/Getshop",
buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.shId + '">' + this.shTitle + '</option>';
});
}
return s + '</select>';
},
}
},
{
editable: true, name: "groupTitle", search: true, stype: "select"
, editrules: { edithidden: true },
search: true,
edittype: 'select',
editoptions: {
dataUrl: "/manager/Products/GetGroups",
buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.grpId + '">' + this.grpTitle + '</option>';
});
}
return s + '</select>';
},
}
},
{
editable: true, width: 70, name: "AvailableCount", search: true, stype: "number",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: true, width: 50, name: "Priority", search: true, stype: "number",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: false, width: 80, name: "ComplementProducts", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: false, width: 70, name: "Images", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: false, width: 100, name: "ProductProperty", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: false, width: 80, name: "Price", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: false, width: 80, name: "Comments", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
{
editable: true, width: 50, name: "Active", search: true, formatter: 'checkbox', edittype: 'checkbox', editoptions: { value: "True:False" }
, formatoptions: { disabled: false}
},
{
editable: true, width: 80, name: "AmazingOffer", search: true, formatter: 'checkbox', edittype: 'checkbox', editoptions: { value: "True:False" }
, formatoptions: { disabled: false}
},
{
editable: true, width: 80, name: "Available", search: true, formatter: 'checkbox', edittype: 'checkbox', editoptions: { value: "True:False" },
searchoptions: { "sopt": ["bw", "eq"] }, formatoptions: { disabled: false }
},
{
name: 'BrandId', align: 'center', hidden: true, viewable: true, editrules: { edithidden: true },
editable: true, stype: 'select',
edittype: 'select',
editoptions: {
dataUrl: "/manager/Products/GetBrands",
buildSelect: function (data) {
var response, s = '<select>', i;
response = jQuery.parseJSON(data);
if (response && response.length) {
$.each(response, function (i) {
s += '<option value="' + this.brandId + '">' + this.brandTitle + '</option>';
});
}
return s + '</select>';
},
}
},
{
name: "myac", width: 80, fixed: true, sortable: false, resize: false, formatter: 'actions',
formatoptions: { keys: true }
},
{
editable: false, width: 70, name: "FullEdit", search: true, stype: "text",
searchoptions: { "sopt": ["bw", "eq"] }
},
// BLAH, BLAH, BLAH
],
gridComplete: function () {
var ids = jQuery("#JQGrid1").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
ComplementProducts = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/ComplementProducts/Index/" + cl + " }) + '><span class=\"fa fa-shopping-cart\" style='color: white;'></span></a></div>";
Images = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/Images/Index/" + cl + " }) + '><span class=\"fa fa-picture-o\" style='color: white;'></span></a></div>";
ProductProperty = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/ProductPropertyItems/Index/" + cl + " }) + '><span class=\"fa fa-braille\" style='color: white;'></span></a></div>";
Price = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/pricesppitems/Index/" + cl + " }) + '><span class=\"fa fa-line-chart\" style='color: white;'></span></a></div>";
Comments = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/Products/Comments/" + cl + " }) + '><span class=\"fa fa-comments\" style='color: white;'></span></a></div>";
FullEdit = "<div class=\"btn-group\"><a class='btn btn-primary' href=/manager/Products/Edit/" + cl + " }) + '><span class=\"fa fa-edit\" style='color: white;'></span></a><a class='btn btn-primary' href=/manager/Products/Details/" + cl + " }) + '><span class=\"fa fa-exclamation-circle\" style='color: white;'></span></a></div>";
jQuery("#JQGrid1").jqGrid('setRowData', ids[i], { ComplementProducts: ComplementProducts, Images: Images, ProductProperty: ProductProperty, Price: Price, Comments: Comments, FullEdit: FullEdit});
}
}, loadComplete: function () {
var activeButton = getColumnIndexByName('Active');
var ids = jQuery("#JQGrid1").jqGrid('getDataIDs'); //id's
$("tbody > tr.jqgrow > td:nth-child(" + (activeButton + 1) + ") > input",
this).click(function (e) {
var rowId = $(e.target).closest("tr").attr("id");
// alert("active clicked " + rowId);
$.ajax({
type: "POST",
url: "/manager/Products/Activate",
data: {
id: rowId
},
dataType: "json"
});
});
var amazingOfferButton = getColumnIndexByName('AmazingOffer');
var ids = jQuery("#JQGrid1").jqGrid('getDataIDs'); //id's
$("tbody > tr.jqgrow > td:nth-child(" + (amazingOfferButton + 1) + ") > input",
this).click(function (e) {
var rowId = $(e.target).closest("tr").attr("id");
$.ajax({
type: "POST",
url: "/manager/Products/ShowInAmazingOffer",
data: {
id: rowId
},
dataType: "json"
});
$('#JQGrid1').trigger('reloadGrid');
});
var availableButton = getColumnIndexByName('Available');
var ids = jQuery("#JQGrid1").jqGrid('getDataIDs'); //id's
$("tbody > tr.jqgrow > td:nth-child(" + (availableButton + 1) + ") > input",
this).click(function (e) {
var rowId = $(e.target).closest("tr").attr("id");
$.ajax({
type: "POST",
url: "/manager/Products/Available",
data: {
id: rowId
},
dataType: "json"
});
$('#JQGrid1').trigger('reloadGrid');
});
},
height: "auto",
caption: "",
viewrecords: true,
rowNum: 20,
direction: "rtl",
pager: jQuery('#JQGrid1_pager'),
rowList: [10, 20, 30, 40],
toppager: true,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
}).jqGrid('navGrid', '#JQGrid1_pager',
// the buttons to appear on the toolbar of the grid
{ edit: true, add: true, del: true, search: true, refresh: true, view: false, position: "left", cloneToTop: true,searchtext:"جستجو" },
// options for the Edit Dialog
{
width: 450,
editCaption: "ویرایش محصول",
recreateForm: true,
closeAfterEdit: true,
viewPagerButtons: false,
//afterShowForm: populateGroups,
errorTextFormat: function (data) {
return 'Error: ' + data.responseText
}
},
// Add options
{ url: '/TabMaster/Create', closeAfterAdd: true },
// Delete options
{ url: '/manager/Products/Remove' },
{
zIndex: 100,
caption: "جستجوی محصول",
sopt: ['cn']
}
);
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
[HttpPost]
public ActionResult EditProductData(string oper, string title,string groupTitle,string shopTitle,int AvailableCount,int Priority, int? id)
{
if (oper == "add")
{
var product = new Product()
{
Title = title,
};
db.Products.Add(product);
db.SaveChanges();
return Content("true");
}
else if (oper == "del")
{
var product = db.Products.Find(id);
db.Products.Remove(product);
return Content("true");
}
else if (oper == "edit")
{
var product = db.Products.Find(id);
product.Title = title;
product.GroupId = int.Parse(groupTitle);
product.ShopId = int.Parse(shopTitle);
product.AvailableCount = AvailableCount;
product.Priority = Priority;
db.SaveChanges();
return Content("true");
}
return Content("false");
}