前端頁面需要有一個動態增加表格行的功能,引用了table.addrow.js這個jquery插件,每一行有一個checkbox,name統一為cbMaintainRatio,而鑒於這部分是一個純Html Form的提交非用戶控件,所以我們在后端使用Request.Form來獲取值,但問題出來了:
<table border="1" class="atable"> <tbody><tr class="evenRow"> <th> width(px) </th> <th> height(px) </th> <th>maintain ratio</th> <th></th> </tr> <tr class="cloneRow9674 oddRow"> <td> <input type="text" size="25" name="imgwidth"> </td> <td> <input type="text" size="25" name="imgheight"> </td> <td> <input type="checkbox" name="maintainratio"> </td> <td class="btnCol"> <input type="button" value="Remove" class="delRow delRow9674" style="display: inline-block;"> </td> </tr><tr class="cloneRow9674 evenRow"> <td> <input type="text" size="25" name="imgwidth"> </td> <td> <input type="text" size="25" name="imgheight"> </td> <td> <input type="checkbox" name="maintainratio"> </td> <td class="btnCol"> <input type="button" value="Remove" class="delRow delRow9674" style="display: inline-block;"> </td> </tr><tr class="cloneRow9674 oddRow"> <td> <input type="text" size="25" name="imgwidth"> </td> <td> <input type="text" size="25" name="imgheight"> </td> <td> <input type="checkbox" name="maintainratio"> </td> <td class="btnCol"> <input type="button" value="Remove" class="delRow delRow9674" style="display: inline-block;"> </td> </tr> <tr class="evenRow"> <td colspan="4"><input type="button" value="Add" class="alternativeRow addRow9674"></td> </tr> </tbody></table>
如果我們有多行表單,也就是有多個name為cbMaintainRatio的checkbox,post到后端的form,我們通過Request.Form["cbMaintainRatio"]只能獲取到一個值"on",而不是像<input type="text" name="width" />這種獲取到的"100,200,"值。
瀏覽了一遍addrow插件的文檔,他竟然不支持event,好吧...那只能我們自己來改造代碼了:
頁面增加一個hidden input,目的為保存多個checkbox的值,如果選中則設定為true,否則false,然后用,分割賦值給這個hidden input
function setMaintainRatio() { var fields; $(':checkbox:checked').each(function () { var txt = $("input[name='cbMaintainRatioList']"); fields = ($(':checkbox').map(function () { if (this.checked) return "true"; else return "false"; }).get().join(",")); $(txt).val(fields); }); }
提交Form的按鈕綁定上面這個js 方法:
<asp:Button ID="btwImageCreate" runat="server" Text="Image Create" OnClick="btwImageCreate_Click" OnClientClick="setMaintainRatio(); return true" /> <input type="hidden" name="cbMaintainRatioList" />
OK,這樣我們就可以在后台代碼通過Request.Form的形式獲取到每一行這個name="cbMaintainRatio" checkbox的值了!