Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete rows of table on checking of checkboxes

Tags:

asp.net-mvc

I have table containing data . In every row there is a checkbox plus a checkbox to select all checkbox at the headers. Upon checking this checkboxes,corresponoding rows are to be deleted from database table.Plus,on chiecking the checkbox at the header,all rows will be deleted from the database table.How can i achieve this asp.net mvc.

like image 970
andrew Sullivan Avatar asked Sep 08 '10 06:09

andrew Sullivan


1 Answers

As always start with a model:

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

Then a controller:

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

And finally the Index.aspx view:

<% 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" />

<% } %>

And the product editor template (~/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>
like image 168
Darin Dimitrov Avatar answered Oct 20 '22 12:10

Darin Dimitrov