【问题标题】:How to delete multiple rows in Jqgrid MVC如何在 Jqgrid MVC 中删除多行
【发布时间】:2017-07-12 01:33:41
【问题描述】:

我的视图由外部 javascript 而非视图本身显示。如何删除 jqgrid 中的多行?我有 multiselectmultiboxonlyset 等于 true。这是我的代码

视图(视图格式为“~/Scripts/TodoList.js”)

@{
    ViewBag.Title = "Index";
}

<h2>TodoList</h2>

<div>
<table id="grid"></table>
<div id="pager"
</div>

<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

<a href="javascript:void(0)" id="m1">Get Selected id's</a>

<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />


<script src="~/Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
@*<script src="~/Scripts/jquery-1.12.4.min.js" type ="text/javascript"></script>*@
<script src="~/Scripts/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="~/Scripts/TodoList.js" type="text/javascript"></script>

Todolist.js (Jqgrid)

/* File Created: February 17, 2017 */
$(function () {
    $("#grid").jqGrid({
        url: "/TodoList/GetTodoLists",
        datatype: 'json',
        mtype: 'Get',       
        colNames: ['Id', 'Task Name', 'Task Description', 'Target Date', 'Severity', 'Task Status'],
        colModel: [
            { key: true, hidden: true, name: 'Id', index: 'Id', editable: true },
            { key: false, name: 'TaskName', index: 'TaskName', editable: true },
            { key: false, name: 'TaskDescription', index: 'TaskDescription', editable: true },
            {
                key: false, name: 'TargetDate', id: "elem", index: 'TargetDate', editable: true, formatter: 'date', formatoptions: { newformat: 'd/m/Y' },
                editoptions: { dataInit: function (elem) { $(elem).datepicker(); } }
            },
            { key: false, name: 'Severity', index: 'Severity', editable: true, edittype: 'select', editoptions: { value: { 'L': 'Low', 'M': 'Medium', 'H': 'High'}} },
            { key: false, name: 'TaskStatus', index: 'TaskStatus', editable: true, edittype: 'select', editoptions: { value: { 'A': 'Active', 'I': 'InActive'}}}],
        pager: jQuery('#pager'),
        rowNum: 10,
        rowList: [10, 20, 30, 40],
        height: '100%',
        viewrecords: true,
        // Bug Codes
       //  loadonce:true, //compulsory for search        
        //cellEdit: true,         //inline edits
        //cellsubmit: 'clientArray', //inline edit
        caption: 'Todo List',
        sortname: 'id',
        sortorder: 'desc',
        multiselect: true,
        multiboxonly: true,
        emptyrecords: 'No records to display',
        jsonReader: {
            root: "rows",
            page: "page",
            total: "total",
            records: "records",
            repeatitems: false,
            Id: "0"
        },
        autowidth: true,        
    }).navGrid('#pager', { edit: true, add: true, del: true, search: true, refresh: true }, //search: true       
        {
            // edit options
            zIndex: 100,
            url: '/TodoList/Edit',
            closeOnEscape: true,
            closeAfterEdit: true,
            recreateForm: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            // add options
            zIndex: 100,
            url: "/TodoList/Create",
            closeOnEscape: true,
            closeAfterAdd: true,
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        },
        {
            //delete options
            zIndex: 100,
            url: "/TodoList/Delete" + ,
            closeOnEscape: true,
            closeAfterDelete: true,
            recreateForm: true,
            msg: "Are you sure you want to delete this task?",
            afterComplete: function (response) {
                if (response.responseText) {
                    alert(response.responseText);
                }
            }
        });                  
});

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using TodoListApplication.DBContext;
using TodoListApplication.Models;

namespace TodoListApplication.Controllers
{
    public class TodoListController : Controller
    {
        //
        // GET: /TodoList/

        public ActionResult Index()
        {
            return View();
        }
        TodoContext db = new TodoContext();
        public JsonResult GetTodoLists(string sidx, string sord, int page, int rows)  //Gets the todo Lists.
        {
            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            var todoListsResults = db.TodoLists.Select(
                    a => new
                    {
                        a.Id,
                        a.Severity,
                        a.TargetDate,
                        a.TaskDescription,
                        a.TaskName,
                        a.TaskStatus
                    });
            int totalRecords = todoListsResults.Count();
            var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
            if (sord.ToUpper() == "DESC")
            {
                todoListsResults = todoListsResults.OrderByDescending(s => s.TaskName);
                todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
            }
            else
            {
                todoListsResults = todoListsResults.OrderBy(s => s.TaskName);
                todoListsResults = todoListsResults.Skip(pageIndex * pageSize).Take(pageSize);
            }
            var jsonData = new
            {
                total = totalPages,
                page,
                records = totalRecords,
                rows = todoListsResults
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        // TODO:insert a new row to the grid logic here
        [HttpPost]
        public string Create([Bind(Exclude = "Id")] TodoList objTodo)
        {
            string msg;
            try
            {
                if (ModelState.IsValid)
                {
                    db.TodoLists.Add(objTodo);
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successful";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }
            return msg;
        }
        public string Edit(TodoList objTodo)
        {
            string msg;
            try
            {
                if (ModelState.IsValid)
                {
                    db.Entry(objTodo).State = EntityState.Modified;
                    db.SaveChanges();
                    msg = "Saved Successfully";
                }
                else
                {
                    msg = "Validation data not successfull";
                }
            }
            catch (Exception ex)
            {
                msg = "Error occured:" + ex.Message;
            }
            return msg;
        }      

        public string Delete(int Id)
        {
            TodoList todolist = db.TodoLists.Find(Id);
            db.TodoLists.Remove(todolist);
            db.SaveChanges();
            return "Deleted successfully";
        }

    }
}

【问题讨论】:

    标签: javascript jquery asp.net-mvc jqgrid


    【解决方案1】:

    jqGrid 在multiselect: true 模式下删除行时发送逗号分隔的 id 列表。因此,您应该将string Delete(int Id) 更改为void Delete(string id)。对应的代码大概如下:

    public void Delete(string id)
    {
        var ids = id.Split(',');
        foreach (var id in ids) {
            TodoList todolist = db.TodoLists.Find(int.Parse(id));
            db.TodoLists.Remove(todolist);
        }
        db.SaveChanges();
    }
    

    我建议您也考虑使用loadonce: true 选项并简化您一次性返回所有 项。这是显示少量行(例如少于 1000)的最佳方案。它将简化您的服务器代码并提高网格的性能(责任)。

    我建议您另外验证您是否使用最新版本的free jqGrid(您可以从NuGet 下载或直接从CDN 加载)。您应该查看您使用的 jqGrid 选项,并删除不需要或错误的选项/参数。

    【讨论】:

    • 它说“对象引用未设置为对象的实例”。故障排除提示建议我使用 new 关键字来创建对象实例。我的 jqgrid 也是最新版本。
    • @Jesse:这是您在 C# 代码(服务器端代码)或 JavaScript 代码(客户端代码)中得到的错误。您在代码的哪一行收到错误?可能您需要将 csvIds 参数重命名为 id (请参阅我的答案的更新代码)?
    • 抱歉回复晚了。它是 C# 代码,即使我将“csvIds”重命名为 id,输出仍然是名称。我还调试了代码,结果“字符串 id”参数没有收到任何值...
    • 嗨@Oleg,我已经设法解决了我的问题。事实证明,您的方法有效,只是控制器传递的 id 名称与我在删除方法参数中指定的 id 不相符。非常感谢! :) 我会在我的回答中附上详细的解释。
    • @Jesse:不客气!很高兴问题现在解决了。
    【解决方案2】:

    在@Oleg 代码的帮助下,我已经解决了我的问题。

    第一个: 我发现我的控制器用来传递 id 的 id 名称是“id”,而我的控制器中的删除方法是“Id”:

     public string Delete(int Id) // < see this
            {
                TodoList todolist = db.TodoLists.Find(Id);
                db.TodoLists.Remove(todolist);
                db.SaveChanges();
                return "Deleted successfully";
            }
    

    click here to see the debug result, pay attention to Form Data Section

    所以控制器指定的 id 和我在删除方法中指定的 id 之间存在名称不匹配

    第二: 所以我将控制器中的删除方法修改为:

    public ActionResult Delete(string id)
            {
                var ids = id.Split(',');
                foreach (var idsss in ids)
                {
                    TodoList todolist = db.TodoLists.Find(int.Parse(idsss));
                    db.TodoLists.Remove(todolist);
                }
                db.SaveChanges();
    
                var result = new { msg = "Deletion Successful ! " };
                return Json(result, JsonRequestBehavior.AllowGet);
            }
    

    现在它可以工作了,感谢@Oleg!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 2013-08-22
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 2010-12-17
      相关资源
      最近更新 更多