2017-02-22 165 views
0

我的视图是通过外部javascript而不是视图本身显示的。我如何删除jqgrid中的多行?我将multiselectmultiboxonly设置为等于true。这是我的代码如何删除Jqgrid中的多行MVC

视图(视图中 “〜/脚本/ 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"; 
     } 

    } 
} 

回答

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

+0

它说“对象引用未设置为对象的实例”。故障排除提示表明我使用new关键字来创建一个对象实例。 我的jqgrid也在其最新版本。 – Jesse

+0

@Jesse:这是你的C#代码(服务器端代码)还是JavaScript代码(客户端代码)中的错误。你的代码中哪一行出现错误?可能您需要将'csvIds'参数重命名为'id'(请参阅我的答案的更新代码)? – Oleg

+0

对不起,延迟回复。这是C#代码,即使我已将“csvIds”重命名为id,输出仍然是名称。 我也调试了代码,结果“字符串id”参数收到没有值... – Jesse

0

我已通过@Oleg代码帮助解决了我的问题。

1: 我发现我的控制器使用通过该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和我在删除方法指定

2号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!