在 ASP.NET Web Forms 中,CheckBoxList 是最常用來做「多選條件」的伺服器控制項。但只要把它排成水平,就會遇到兩個麻煩:選項之間黏得太緊不好看,以及前端與後端各自該怎麼把「使用者到底勾了哪些」讀出來。以下把樣式、jQuery 取值、C# 取值三件事一次整理清楚。
要讓選項由左到右排列,關鍵是 RepeatDirection="Horizontal" 搭配 RepeatLayout="Flow"。若沿用預設的 Table 版型,每個項目都會被包進一格 table cell,樣式不易控制;改成 Flow 則是純行內輸出,後續交給 CSS 排版自由度高得多。
<asp:CheckBoxList ID="ddlplatform" runat="server"
RepeatDirection="Horizontal" RepeatLayout="Flow"
CssClass="checkboxlist">
<asp:ListItem Value="APP">APP</asp:ListItem>
<asp:ListItem Value="移動觸屏">移動觸屏</asp:ListItem>
<asp:ListItem Value="PC">PC</asp:ListItem>
<asp:ListItem Value="微信">微信</asp:ListItem>
<asp:ListItem Value="微博">微博</asp:ListItem>
</asp:CheckBoxList>
Flow 版型會為每個項目輸出一組 label,直接對 label 下 margin 就能拉開距離,不必去動控制項本身。
.checkboxlist label
{
margin-right: 20px;
}
控制項渲染成 HTML 之後,每個選項都是一個 input:checkbox,而顯示文字位於緊鄰在後的 label 之中,因此用 next() 抓文字最為直觀。
var labels = [];
$("#ddlplatform input:checkbox:checked").each(function () {
labels.push($(this).next().html());
});
var result = labels.join(",");
這裡刻意把原始的 var label; 改成陣列。原寫法變數未初始化就使用 +=,第一輪會拼出「undefined」開頭的字串;改用陣列再以 join 合併,或至少先給定空字串,都能避免這個坑。另外若只要「值」不要「文字」,直接取 $(this).val() 即可。
// 使用平台
string Platfrom = string.Empty;
foreach (ListItem li in this.ddlplatform.Items)
{
if (li.Selected)
{
Platfrom += li.Text + ",";
}
}
Platfrom = Platfrom.TrimEnd(',');
邏輯很單純:走訪 Items 集合,把 Selected 為 true 的項目文字串接起來,最後用 TrimEnd(',') 去掉多餘的尾端逗號。若要收集 Value,把 li.Text 換成 li.Value;在 .NET 4.0 以上也可以寫得更精簡:
string platfrom = string.Join(",",
ddlplatform.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value));
這種 LINQ 寫法不必手動處理分隔符號,也少了空集合時多切一刀的判斷。