在 ASP.NET 裡,CheckBoxList 綁定資料後,前端 HTML 只會渲染出 text,並不會保留 value,這讓我們很難直接用 jQuery 取得每個選項的值。解法是:在後端為每個 ListItem 動態加上一個自訂屬性(這裡用 alt),前端再透過這個屬性間接取值。
$("#<%=cbxStyle.ClientID %> input:checkbox").each(function(){
if(this.checked == true)
alert($(this).parent("span").attr("alt"));
});
<asp:CheckBoxList ID="cbxStyle" runat="server" RepeatColumns="3"
RepeatDirection="Horizontal">
</asp:CheckBoxList>
cbxStyle.DataSource = ds.Tables[0];
cbxStyle.DataTextField = "stylename";
cbxStyle.DataValueField = "styleid";
cbxStyle.DataBind();
foreach (ListItem li in cbxStyle.Items)
{
li.Attributes.Add("alt", li.Value);
}
關鍵就在最後的 foreach:DataBind 之後,逐一把每個項目的 Value 塞進 alt 屬性。如此一来,前端只要讀取父層 span 的 alt,就能拿到對應的 styleid,順利解決 CheckBoxList 沒有 value 的難題。