本文示範如何在 ASP.NET 的三層架構中,用 jQuery 完成 GridView 列表的全選、反選,並搭配後端做批量刪除。
ASPX 頁面:
<script src="Jquery1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#Checkbox1').click(function () {
if ($('#Checkbox1').is(':checked')) {
$('td input').attr('checked', true); // 全選
}
else { $('td input').attr('checked', false); }
})
$('#Checkbox2').click(function () {
$('td input').each(function () {
$(this).attr('checked', !$(this).attr('checked')) // 反選
})
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Checkbox1" type="checkbox" />全選<input id="Checkbox2" type="checkbox" />反選<asp:Button
ID="Button1" runat="server" Text="刪除" onclick="Button1_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="選擇">
<ItemTemplate>
<asp:CheckBox ID="CheckBox3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="編號" />
<asp:BoundField DataField="NewsTitle" HeaderText="標題" />
<asp:BoundField DataField="NewsContent" HeaderText="新聞內容">
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="NewsCreator" HeaderText="創建者" />
<asp:BoundField DataField="CreateTime" HeaderText="創建時間" />
</Columns>
</asp:GridView>
</div>
</form>
後台 CS 檔案:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
load();
}
}
private void load() // 實現綁定
{
Jquery三層實現刪除功能.Model.T_News mm = new Model.T_News();
Jquery三層實現刪除功能.BLL.T_News bb = new BLL.T_News();
string sqlwhere = "Id<25";
ds = bb.GetList(sqlwhere); // 獲取 dataset 綁定
this.GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
// 遍歷每一行
foreach (GridViewRow item in GridView1.Rows) // 注意這裡是 GridViewRow 而非 DataRow
{
CheckBox cb = (CheckBox)item.FindControl("CheckBox3"); // 找到這個選中項
if (cb.Checked) // 選中
{
Jquery三層實現刪除功能.BLL.T_News bb = new BLL.T_News();
if (bb.DeleteList(item.Cells[1].Text)) // 調用 bb.DeleteList(id) 刪除
{
Response.Write("刪除成功");
}
load();
}
}
}
前端用 jQuery 控制全選與反選,後端則在按鈕事件裡遍歷 GridView 的每一列,取出核取方塊狀態並呼叫業務邏輯層的刪除方法,最後重新繫結資料刷新列表,形成完整的批量刪除流程。