ASP.NET点击CheckBox按isActive属性隐藏DataList对应项的问题
问题原因
- 你前端定义的
<table>没有添加runat="server"属性,属于普通HTML元素,服务器端FindControl方法无法识别,获取到的对象为null,设置Visible自然不生效;且加了runat="server"的原生HTML table对应的服务端类型是HtmlTable,不是Table类,类型转换失败也会导致空引用。 - CheckBox控件没有添加
AutoPostBack="true"属性,点击后不会触发页面回发,后台filterByActive事件根本不会执行。 - 你判断Label文本时用的是转义字符
Disabled ❌,但页面渲染后服务器端拿到的Label.Text已经是解析后的带实际emoji的文本,字符串匹配会失败。 - CheckBox取消勾选的逻辑有问题,原来的写法只把激活项设为可见,之前被隐藏的禁用项没有恢复可见,会导致禁用项一直处于隐藏状态。
修正后代码
前端代码
<asp:CheckBox runat="server" Text="Filter by active postings" OnCheckedChanged="filterByActive" AutoPostBack="true"/> <asp:DataList ID="postingsDataList" runat="server" OnItemCommand="itemCommand" > <ItemTemplate> <div class="postingRow"> <table class="postingTable" id="posting" runat="server"> <tr> <td> <asp:Label ID="lblActive" runat="server" Text='<%#Eval("isActive").ToString().Equals("True") ? "Active ✅" : "Disabled ❌"%>'/> </td> </tr> </table> </div> </ItemTemplate> </asp:DataList>
后端代码
using System.Web.UI.HtmlControls; protected void filterByActive (object sender, EventArgs e) { int count = postingsDataList.Items.Count; CheckBox check = (CheckBox)sender; for (int i = 0; i < count; i++) { Label lblActive = postingsDataList.Items[i].FindControl("lblActive") as Label; HtmlTable tbl = postingsDataList.Items[i].FindControl("posting") as HtmlTable; if(tbl == null || lblActive == null) continue; if (check.Checked) { tbl.Visible = !lblActive.Text.Contains("Disabled"); } else { // 取消筛选时所有项恢复可见 tbl.Visible = true; } } }
内容的提问来源于stack exchange,提问作者notGoodAtThis
相关产品推荐
相关产品推荐

