delete rows of table on checking of checkboxes
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.
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>
I would use AJAX. On changing the checked state, I would submit a request to delete all the selected IDs and refresh the table data.
Use jQuery
, some other javascript library, or just hand code an AJAX request on check of checkbox. Then alter the DOM
on success.
Using jQuery you could do something like:
<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();
}
});
)};
This is very basic implementation, you could dress it up with some animation in the removal of the row. You also need to pass data and return data with some error handling. Check out here for a jQuery AJAX tutorial.
精彩评论