检查复选框时删除表行

时间:2010-09-08 06:43:47

标签: asp.net-mvc

我有包含数据的表。在每一行中都有一个复选框和一个复选框,用于选择标题处的所有复选框。 选中此复选框后,将从数据库table.Plus中删除对应的行,在清除标题上的复选框时,所有行都将从数据库表中删除。如何实现此asp.net mvc。

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

我会使用AJAX。在更改已检查状态时,我将提交删除所有选定ID的请求并刷新表数据。

答案 2 :(得分: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

相关问题