如何删除Jqgrid MVC中的多行

时间:2017-02-22 06:20:37

标签: javascript jquery asp.net-mvc jqgrid

我的视图由外部JavaScript而不是视图本身显示。如何在jqgrid中删除多行?我将multiselectmultiboxonly设置为等于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";
        }

    }
}

2 个答案:

答案 0 :(得分:2)

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选项,并删除不需要的或错误的选项/参数。

答案 1 :(得分:0)

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

第一: 我发现我的控制器用来传递id的id名称是“id”,而我的控制器中的delete方法是“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!