转自:http://www.cnblogs.com/Fred_Xu/archive/2013/01/16/how-to-get-the-checkbox-value-from-a-dynamically-generated-checkbox-list-asp-net.html
前端页面需要有一个动态增加表格行的功能,引用了table.addrow.js这个jquery插件,每一行有一个checkbox,name统一为cbMaintainRatio,而鉴于这部分是一个纯Html Form的提交非用户控件,所以我们在后端使用Request.Form来获取值,但问题出来了:
<table border=" 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=" name="imgwidth"> </td> <td> <input type=" 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=" name="imgwidth"> </td> <td> <input type=" 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=" name="imgwidth"> </td> <td> <input type=" 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="><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;
$("input[name='cbMaintainRatio']").each(function () {
var txt = $("input[name='cbMaintainRatioList']");
fields = ($("input[name='cbMaintainRatio']").map(function () {
if (this.checked)
return "1";
else
return "0";
}).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的值了!
全部和已选择比较
; i < Model[].Count; i++) { bool c = false; ; j < Model[].Count; j++) { ][j].ButtonID == Model[][i].ButtonID) { c = true; break; } } if (c) { <div class="check-box"> <input name="btns" id="Model[0][i].ButtonID" checked="checked" class="input-text" type="checkbox" style="width: 100px" autocomplete="off" /> <lable>Model[][i].Name</lable> </div> } else { <div class="check-box"> <input name="btns" id="Model[0][i].ButtonID" class="input-text" type="checkbox" style="width: 100px" autocomplete="off" /> <lable>Model[][i].Name</lable> </div> } }