选中多个复选框时选择从数据库

时间:2012-08-03 14:19:16

标签: c# database checkbox

当多个复选框时,如何从数据库中选择多行 已经过检查。这是code.if你看我使用查询字符串的行 有双重请求,我不知道还有什么我必须插入。

@{
    var db = Database.Open("Checkbox");
    var sql = "SELECT * FROM Brands";
    var select = db.Query(sql);
    dynamic execute = "";
    List<String> selected = new List<string>();
    int count = 0;
    List<dynamic> exec = new List<dynamic>();


    if(IsPost){
        if(Request["List"] == null){
            Response.Redirect("~/Checkbox");
        }
        selected = Request["List"].Split(',').ToList();

        count = Request["List"].Count();

        var sqls = "SELECT * FROM Brands WHERE Name = @0 OR Name = @1";
        exec = db.Query(sqls, Request["List"], Request["List"]);



}

<!DOCTYPE html>
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Checkbox Multiple</title> 
</head>
<body>
    @foreach(var values in exec){
        <span>@values.BrandID</span>
    }

    <form method="post" action="">
    @foreach(var item in select){
    <label>@item.Name</label>     
    <input type="checkbox" multiple="multiple" name="List" value="@item.Name"><br>
    }
    <input type="submit" value="Send">    
        </form>
</body>


</html>

2 个答案:

答案 0 :(得分:0)

您可以尝试在查询中使用并构造逗号分隔的字符串并在查询中弹出它。

string inClause = "1, 2, 3";

var sqls = "SELECT * FROM Brands WHERE Name in (" + inClause +")";

答案 1 :(得分:0)

您可以创建一个分割昏迷分隔列表的SQL函数

    SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[Split]      
(      
 @RowData varchar(8000),      
 @SplitOn nvarchar(5)      
)       
RETURNS @RtnValue table      
(      
 Id int identity(1,1),      
 Data nvarchar(100)      
)      
AS       
BEGIN      
 Declare @Cnt int      
 Set @Cnt = 1      

 While (Charindex(@SplitOn,@RowData)>0)      
 Begin      
  Insert Into @RtnValue (data)      
  Select      
   Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))      

  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))      
  Set @Cnt = @Cnt + 1      
 End      

 Insert Into @RtnValue (data)      
 Select Data = ltrim(rtrim(@RowData))      

 Return      
END      

现在您可以将逗号分隔列表传递给此函数。

假设 @configIds ='1,2,3,4,6,17' 它将为每个ID分别插入数据

 INSERT INTO ABC      
(ID,patient_id,created_user,created_date)      
SELECT data, @patient_Id, @created_user, Getdate()FROM Split(@configIds,',')  

或更新新复选框列表所选记录时可以使用它 首先删除不在逗号分隔列表中的记录(@configIds)

DELETE FROM ABC WHERE ID IN                     
( SELECT DISTINCT ID FROM ABC WHERE Patient_ID=@patient_Id                                       
AND ID NOT in (SELECT Ltrim(Rtrim(Data)) FROM Split(@configIds,','))                    
)   

更新代码.....

删除块后将Update标志设置为true或根据新选中的复选框列表记录更新记录