2017-02-22 2 views
0

내보기가 뷰 자체가 아니라 외부 자바 스크립트에 의해 표시됩니다. jqgrid에서 여러 행을 어떻게 삭제합니까? 나는 multiselectmultiboxonly을 true로 설정했습니다. 여기 이 Jqgrid에서 여러 행을 삭제하는 방법 MVC

보기

내 코드

@{ 
    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) (뷰가 "~/스크립트/TodoList.js"에 포맷)이 있습니다

/* 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)으로 변경해야합니다. 해당 코드는 다음에 대해 수 : 난 당신이 너무 고려 loadonce: true 옵션을 사용하는 것이 좋습니다 것와 공동으로 한 번에 모든 항목을 반환 단순화하기 위해

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(); 
} 

. 적은 수의 행을 표시 할 때 가장 좋은 시나리오입니다 (예 : 1000 이하). 서버 코드를 단순화하고 그리드의 성능 (책임)을 향상시킵니다.

최신 버전의 free jqGrid (NuGet에서 다운로드하거나 CDN에서 직접 다운로드 할 수 있음)을 추가로 인증하는 것이 좋습니다. 불필요하거나 잘못된 옵션/매개 변수를 제거하고 제거하는 jqGrid 옵션을 검토해야합니다.

+0

"개체 참조가 개체의 인스턴스로 설정되지 않았습니다"라고 표시됩니다. 문제 해결 팁은 새 키워드를 사용하여 개체 인스턴스를 만드는 것이 좋습니다. 내 jqgrid도 최신 버전입니다. – Jesse

+0

@Jesse : C# 코드 (서버 측 코드) 또는 JavaScript 코드 (클라이언트 측 코드)에서 오류가 발생합니까? 어떤 코드 줄에서 오류가 발생합니까? 아마도'csvIds' 매개 변수의 이름을'id'로 바꿔야 할 것입니다 (내 대답의 업데이트 된 코드를보십시오)? – Oleg

+0

늦게 답변을 드려 죄송합니다. 그것은 C# 코드 및 ID에 'csvIds'이름을 바꿀 경우 출력 여전히 이름입니다. 또한 코드를 디버깅하여 "문자열 ID"매개 변수가 값을받지 못하는 것으로 나타났습니다 ... – Jesse

0

@Oleg 코드의 도움으로 문제를 해결했습니다. 1

:

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의 이름이 "ID가"이라고 발견

컨트롤러에서 지정한 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 덕분에 이제 작동합니다!