实现思路主要依托了sql server 的IN函数
IN 操作符允许我们在 WHERE 子句中规定多个值。比and方便得多
准备测试数据
use master
go
if exists(select 'x' from sys.databases where name='checkbox')
drop database checkbox
go
create database checkbox
go
use checkbox
go
if exists(select 'x' from sys.tables where name='checkboxInfo')
drop table checkboxInfo
go
create table checkboxInfo(
ID int primary key identity(1000,1),
checkType varchar(10) not null,
checkName varchar(50) not null
)
go
insert into checkboxInfo values('10','数据1')
insert into checkboxInfo values('20','数据2')
insert into checkboxInfo values('30','数据3')
B/S思路
<div>
<input id="check1" type="checkbox" value="10" />员工
<input id="check2" type="checkbox" value="20" />组长
<input id="check3" type="checkbox" value="30" />经理
</div>
$("input[type=checkbox]").change(function () {
var checkbox = "";
$("input[type='checkbox']:checked").each(function (index, item) {
if ($("input[type='checkbox']:checked").length - 1 == index) {
checkbox += $(this).val();
} else {
checkbox += $(this).val() + ",";
}
});
$.ajax({
type: "post",
url: "AshxAll.ashx",
data: { checkType: checkbox },
dataType: "json",
success: function (data) {
//展示数据
}
});
});
后台:接受到的值是 "10,20"这种形式,再使用字符串拼接成下面这种就可以实现多选查询,不管怎么选都行。
select checkType,checkName from checkboxInfo where checkType in (checkType)
//既是select checkType,checkName from checkboxInfo where checkType in (10,20,30)
C/S思路
这里也是使用逗号拼接,不过c/s没有value,我是从控件名上获取value,我这里的命名是checkType10,checkType20等等
Dim cksql As String = ""
For Each c As CheckBox In Panel3.Controls
c.Enabled = True
If c.Checked Then
cksql += "," + c.Name.Replace("checkType", "")
End If
Next
If cksql = "" Then
cksql = " and checkTypein(10,20,30) "
Else
cksql = " and checkType in(" + cksql.Remove(0, 1) + ") "
End If
后面有一步是需要去除前面的逗号,不然程序会报错。