2010-09-08 132 views
5

我有包含數據的表。在每一行中都有一個複選框和一個複選框,用於選擇標題中的所有複選框。 選中此複選框後,相應的行將從數據庫table.Plus中刪除,在chiecking標題中的複選框時,所有行都將從數據庫表中刪除。如何才能實現此asp.net mvc。刪除複選框檢查表的行

回答

9

像往常一樣與模型開始:

public class ProductViewModel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

然後控制器:

public class HomeController : Controller 
{ 
    // TODO: Fetch this from a repository 
    private static List<ProductViewModel> _products = new List<ProductViewModel> 
    { 
     new ProductViewModel { Id = 1, Name = "Product 1" }, 
     new ProductViewModel { Id = 2, Name = "Product 2" }, 
     new ProductViewModel { Id = 3, Name = "Product 3" }, 
     new ProductViewModel { Id = 4, Name = "Product 4" }, 
     new ProductViewModel { Id = 5, Name = "Product 5" }, 
    }; 

    public ActionResult Index() 
    { 
     return View(_products); 
    } 

    [HttpPost] 
    public ActionResult Delete(IEnumerable<int> productIdsToDelete) 
    { 
     // TODO: Perform the delete from a repository 
     _products.RemoveAll(p => productIdsToDelete.Contains(p.Id)); 
     return RedirectToAction("index"); 
    } 
} 

最後的Index.aspx觀點:

<% using (Html.BeginForm("delete", "home", FormMethod.Post)) { %> 

    <table> 
     <thead> 
      <tr> 
       <th>Name</th> 
       <th>Select</th> 
      </tr> 
     </thead> 
     <tbody> 
      <%= Html.EditorForModel()%> 
     </tbody> 
    </table> 

    <input type="submit" value="Delete selected products" /> 

<% } %> 

而且產品編輯模板(~/Views/Home/EditorTemplates/ProductViewModel.ascx) :

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<ToDD.Controllers.ProductViewModel>" %> 
<tr> 
    <td> 
     <%: Model.Name %> 
    </td> 
    <td> 
     <input type="checkbox" name="productIdsToDelete" value="<%: Model.Id %>" /> 
    </td> 
</tr> 
+0

感謝Darin,它工作。 – 2010-09-08 08:07:44

+0

我不明白複選框的值如何確定,請您解釋一下嗎?我對MVC很陌生,並試圖找出它。謝謝。 – Shimmy 2012-11-05 23:22:33

0

我會使用AJAX。在更改檢查狀態時,我會提交一個請求來刪除所有選定的ID並刷新表格數據。

+0

意味着如果在檢查複選框時,將會發出ajax調用並且表將被重新調用,然後再次檢查其他複選框時會發生同樣的事情。 – 2010-09-08 06:53:55

+0

@andrew Sullivan yes – thelost 2010-09-08 07:04:12

0

使用jQuery,一些其他的JavaScript庫,或只是手動檢查複選框的AJAX請求代碼。然後在成功時更改DOM

使用jQuery,你可以這樣做:

<table> 
    <tr> 
     <td><input type="checkbox" class="check" id="1" /></td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" class="check" id="2" /></td> 
    </tr> 
    <tr> 
     <td><input type="checkbox" class="check" id="3" /></td> 
    </tr> 
</table> 


$('.check').click(function() { 
    var tableRow = $(this).parent().parent(); 
    var id = $(this).attr('id'); 
    $.ajax({ 
     url: 'http://www.YOURDOMAIN.com/Controller/Action/' + id, 
     success: function(data) { 
      $(tableRow).remove(); 
     } 
    }); 
)}; 

這是非常基本的實現,你可以在去除該行的一些動畫打扮起來。您還需要傳遞數據並返回一些錯誤處理的數據。點擊這裏查看jQuery AJAX tutorial

+0

這是asp.net mvc。我應該如何將信息傳遞給控制器​​,選中哪個複選框。 – 2010-09-08 06:55:18

+0

可能帶有ID,我會用選項發佈一個編輯。在複選框上查看新的URL和ID。然而,我會研究一個JSON網絡服務,更輕,更容易。加上它與MVC很好地工作,因爲有一個'JSONRESULT'動作類型。 – 2010-09-08 07:11:09