在Jqgrid中删除ID始终为0

时间:2013-06-17 10:06:35

标签: jquery asp.net asp.net-mvc jqgrid

JqGrid编辑功能在我的网格中正常工作但删除功能总是将记录ID传递为0。

@model Shop.Models.ShopModels.lstMainCategory
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
    <div id="pager" class="scroll" style="text-align:center;"></div>                                                            

    <script type="text/javascript">

        var myGrid = $('#list');
        $(document).ready(function () {

            $.jgrid.nav.addtext = "Add";
            $.jgrid.nav.edittext = "Edit";
            $.jgrid.nav.deltext = "Delete";
            $.jgrid.edit.addCaption = "Add Main Category";
            $.jgrid.edit.closeAfterAdd = true;
            $.jgrid.edit.closeAfterEdit = true;
            $.jgrid.edit.editCaption = "Edit Main Category";
            $.jgrid.del.caption = "Delete Main Category";
            $.jgrid.del.msg = "Delete selected Main Category?";

            $.extend($.jgrid.edit, {
                beforeSubmit: function () {
                    $(this).jqGrid("setGridParam", { datatype: "json" });
                    return [true, "", ""];
                }
            });

            $("#list").jqGrid({
                url: '/MainCategory/DynamicGridData/',
                datatype: 'json',
                mtype: 'GET',

                colNames: ['Edit', 'Main Category'],
                colModel: [
         { name: 'MaincategoryID', index: 'MaincategoryID', width: 40, align: 'left', /* key: true,*/editable: true, editrules: { edithidden: false }, hidedlg: true, hidden: true },
         { name: 'MainCategoryName', index: 'MainCategoryName', search: true, width: 700, align: 'left', editable: true, edittype: 'text', editrules: { required: true }, formoptions: { elmsuffix: ' *'} }],
                pager: jQuery('#pager'),
                editurl: '@Url.Action("Update", "MainCategory")',
                rowNum: 10,
                width: '100%',
                height: '100%',
                rowList: [5, 10, 20, 50],
                viewrecords: true,
                loadonce: true,
                ignoreCase: true,
                caption: 'Main Categories'

            }).navGrid('#pager', { edit: true, add: true, del: true, search: true, searchtext: "Search" });

            $("#list").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false, defaultSearch: 'cn' });

            $("#list").setGridParam({ data: results.rows, localReader: reader }).trigger('reloadGrid');


    </script>

控制器:

  public ActionResult Update(lstMainCategory viewModel, FormCollection formCollection)
        {
            var operation = formCollection["oper"];
            lstMainCategory mcat = new lstMainCategory();
            rep = new MaincategoryRepository();
            if (operation.Equals("add"))
            {              

                mcat.MainCategoryName = viewModel.MainCategoryName;
                rep.Create(mcat);
                rep.Save();
            }
            else if (operation.Equals("edit"))
            {
                mcat.MaincategoryID = viewModel.MaincategoryID;
                mcat.MainCategoryName = viewModel.MainCategoryName;
                rep.Edit(mcat);
                rep.Save();
            }
            else if (operation.Equals("del"))
            {

                rep.Delete(viewModel.MaincategoryID);//here MaincategoryID is always 0 so it's not working
                rep.Save();
            }

            return Content("true");
        }

修改

MainCategoryID  MainCategory
16           aaa
17           bbb

enter image description here

存储库:

 public object DynamicGridData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            dc = new ShopDataContext(DBConnection.Connection);

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = dc.tblMainCategories.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            List<MainCategory> lst = (from tbm in dc.tblMainCategories
                                select new MainCategory
                                {
                                    MaincategoryID=tbm.MainCategoryID,
                                    MainCategoryName=tbm.MainCategory,
                                    DeleteID=tbm.MainCategoryID
                                }).ToList<MainCategory>().OrderBy(x=>x.MainCategoryName).ToList();

            List<MainCategory> Flst;



            if (_search && searchField == "MainCategory")
            {
                Flst = lst.Where(r => r.MainCategoryName.Contains(searchString)).OrderBy(x => x.MainCategoryName).ToList().ToList();
            }
            else
                Flst = lst;


            var GridData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from mcat in Flst
                    select new
                    {
                        i = mcat.MaincategoryID,
                        cell = new string[] { mcat.MaincategoryID.ToString(), mcat.MainCategoryName.ToString(),mcat.DeleteID.ToString() }
                    }).ToArray()
            };

            return GridData;
        }

1 个答案:

答案 0 :(得分:2)

首先,您应该修复您使用的服务器响应的格式。它具有i属性,但它具有id属性。这条线

i = mcat.MaincategoryID,

必须修复

id = mcat.MaincategoryID,

您可以替换代码

rows = (
    from mcat in Flst
    select new
    {
        i = mcat.MaincategoryID,
        cell = new string[] { mcat.MaincategoryID.ToString(), mcat.MainCategoryName.ToString(),mcat.DeleteID.ToString() }
    }).ToArray()

rows = (
    from mcat in Flst
    select new[] {
        mcat.MaincategoryID.ToString(),
        mcat.MainCategoryName,
        mcat.DeleteID.ToString()
    }).ToArray()

没有重复相同的信息(发送mcat.MaincategoryID两次)并从您发送的每个项目中删除"id:""cell:"字符串。要在客户端读取更紧凑的数据,您应该向jqGrid添加jsonReader: { cell: "" }选项。如果您使用jqGrid的最新版本,则该选项是可选的。

如果您希望发送包含MaincategoryID列的内容,则应使用editrules: { edithidden: true }列中的MaincategoryID选项(请参阅the answer)。或者,您可以添加prmNames: {id: "MaincategoryID"}。在jqGrid将发送rowid作为“MaincategoryID”而不是默认值"id"的情况下。

如果您不需要显示MaincategoryID列,则可以将其从colModel 中删除。在这种情况下,您可以将从服务器返回的数据的顺序更改为

rows = (
    from mcat in Flst
    select new[] {
        mcat.MainCategoryName,
        mcat.MaincategoryID.ToString(),
        mcat.DeleteID.ToString()
    }).ToArray()

jqGrid中的更改将是

colNames: ['Edit', 'Main Category'],
colModel: [
    { name: 'MainCategoryName', width: 700, editable: true,
        editrules: { required: true }, formoptions: { elmsuffix: ' *'} }
],
pager: "#pager",
gridview: true,
jsonReader: {cell: "", id: 1},
prmNames: {id: "MaincategoryID"}

jqGrid为每一行(每id)分配<tr>属性。使用sonReader: {id: 1}通知jqGrid从行数据的第二项(mcat.MaincategoryID.ToString())获取rowid。其他更改pager: "#pager"gridview: true与我之前在the answer中写过的内容相同。您应该从<table id="list" ...<div id="paber" ...中删除额外的垃圾(请参阅我的旧答案)