简体   繁体   English

如何使用ASP.NET MVC在数据库中存储多个选中的Checkbox值

[英]How to store multiple checked Checkbox values in DB using ASP.NET MVC

I am developing a project using ASP MVC and stored procedures (SQL Server), I want to store checked checkbox items in database. 我正在使用ASP MVC和存储过程(SQL Server)开发一个项目,我想将选中的复选框项存储在数据库中。 I've tried to add a List<string> type in model in order to access these value and then store them in the database. 我试图在模型中添加List<string>类型,以便访问这些值,然后将其存储在数据库中。

The problem that the relational databases are designed specifically to store one value per row/column combination. 关系数据库专门设计为每行/列组合存储一个值的问题。 In order to store more than one value, I must serialize my list into a single value for storage, then deserialize it upon retrieval. 为了存储多个值,我必须将列表序列化为单个值进行存储,然后在检索时将其反序列化。

That's my view markup: 那就是我的视图标记:

               <h6>Items</h6>
                    <ul>
                        <li>
                            <label class="anim">
                                <input type="checkbox" class="checkbox" value="Soups" name="Items">
                                <span>Soups</span>
                            </label>
                        </li>
                        <li>
                            <label class="anim">
                                <input type="checkbox" class="checkbox" value="Burger" name="Items" >
                                <span>Burger</span>
                            </label>
                        </li>
                        <li>
                            <label class="anim">
                                <input type="checkbox" class="checkbox" value="Drinks" name="Items">
                                <span>Drinks</span>
                            </label>
                        </li>
                        <li>
                            <label class="anim">
                                <input type="checkbox" class="checkbox" value="Desserts" name="Items">
                                <span>Desserts</span>
                            </label>
                        </li>
                    </ul>

Method AddBestellung : 方法AddBestellung

try
{
    using (SqlConnection con = new SqlConnection(Connection()))
    {
        using (SqlCommand cmd = new SqlCommand("AddNewBestellung", con))
        {
            foreach(var item in bs.Items)
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Items", item);
            }

            // Another saved parameters...

            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i >= 1)
                return true;
            else
                return false;
        }
    }
}
catch(Exception ex)
{
    string e = ex.Message;
    return false;
}

private static string Connection()
{
    return ConfigurationManager.ConnectionStrings["deliverycon"].ToString();
}

Model: 模型:

public List<string> Items { get; set; }

You shouldn't serialize/deserialize. 您不应该序列化/反序列化。 This will be painful to use afterward. 以后使用起来会很痛苦。

Imagine you need to retrieve objects that have items 1 and 5 checked. 想象一下,您需要检索已选中项目1和5的对象。 If it's serialized as a string it's less efficient and easy that to store it as follow. 如果将其序列化为字符串,则按照以下方式存储它的效率和便捷性较低。

Let's say you have a "Person" table and you want to check the list of "Consoles" they own. 假设您有一个“人”表,并且要检查他们拥有的“控制台”列表。

You'll have table person : 您将拥有餐桌人物

  • id int primary key id int主键
  • Name varchar not null 名称varchar不为null

and the table console 和表控制台

  • id int primary_key id int primary_key
  • name varchar not null 名称varchar不为null

and the table to store the console owned : 和存储控制台所拥有的表:

owned_console owned_console

  • id int primary key id int主键
  • person_id int (foreign key => person(id)) person_id int(外键=> person(id))
  • console_id int (foreign key => console(id)) console_id int(外键=> console(id))

In your code, you will insert a record per checkbox checked. 在您的代码中,您将为每个选中的复选框插入一条记录。

Person: 人:

  • (1)Thomas (1)托马斯
  • (2)Pierre (2)皮尔

Console: 安慰:

  • (1)NES (1)NES
  • (2)MegaDrive (2)MEGADRIVE
  • (3)NeoGeo (3)NEOGEO

owned_console: owned_console:

  • (1)(1) (1)(1)
  • (1)(2) (1)(2)
  • (1)(3) (1)(3)

  • (2)(1) (2)(1)

  • (2)(1) (2)(1)

And then you can do things like : 然后,您可以执行以下操作:

SELECT * 
FROM   person p
INNER  JOIN owned_console oc
ON     p.id = oc.person_id
WHERE  oc.console_id IN (3,1);

Flags Enumeration - 标志枚举-

[Flags]
public enum ItemStorage
{
    Soups = 1,
    Burger = 2,
    Drinks = 4,
    Dessert = 8,
    Cheese = 16
}

I added the Cheese just to emphasise the binary nature of the Flags enum. 我添加了Cheese只是为了强调Flags枚举的二进制性质。

And here's your other code - 这是您的其他代码-

public class Stuff
{
    private List<string> Items;
    private static string Connection()
    {
        return ConfigurationManager.ConnectionStrings["deliverycon"].ToString();
    }

    public bool DoStuff()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(Connection()))
            {
                using (SqlCommand cmd = new SqlCommand("AddNewBestellung", con))
                {

                    cmd.Parameters.AddWithValue("@Items", (int)ConstuctEnumValueFromList(Items));
                    //other saved parameters...

                    con.Open();
                    int i = cmd.ExecuteNonQuery();
                    con.Close();

                    if (i >= 1)
                        return true;
                    else
                        return false;
                }
            }
        }
        catch (Exception ex)
        {
            string e = ex.Message;
            return false;
        }
    }

    private ItemStorage ConstuctEnumValueFromList(List<string> list)
    {
        var result = new ItemStorage();
        if (list.Any())
        {
            var separatedList = string.join(",", list)
            bool success = Enum.TryParse<ItemStorage>(separatedList, out result)
        }
        return result;
    }
}

In this case, you can simply store the Items field as a single integer and cast it back to ItemStorage when retrieving like so - 在这种情况下,您可以简单地将Items字段存储为单个整数,并在检索时将其转换回ItemStorage,如下所示:

int i = 1 + 2 + 4 + 8;
var items = (ItemStorage)i;
Console.WriteLine(items.ToString());

This should give you "Soups, Burger, Drinks, Desserts"; 这应该给您“汤,汉堡,饮料,甜点”;

XML Serialization XML序列化

First, make sure you're familiar with this document . 首先,请确保您熟悉本文档 This method requires that you store your Items collection to an XML column in SQL Server. 此方法要求您将Items集合存储到SQL Server中的XML列。 It also has the advantage that you can query against that column, provided you're not afraid of SQLXML and XPath. 如果您不担心SQLXML和XPath,它还有一个优点是可以针对该列进行查询。 Many developers are. 有很多开发人员。

Once you have that, everything looks very similar (if a little simpler). 一旦有了它,一切看起来都非常相似(如果简单一点)。

public class Stuff
{
    private List<string> Items;
    private static string Connection()
    {
        return ConfigurationManager.ConnectionStrings["deliverycon"].ToString();
    }

    public bool DoStuff()
    {
        try
        {
            using (SqlConnection con = new SqlConnection(Connection()))
            {
                using (SqlCommand cmd = new SqlCommand("AddNewBestellung", con))
                {

                    cmd.Parameters.AddWithValue("@Items", ConstructXmlFromList(Items));
                    //other saved parameters...

                    con.Open();
                    int i = cmd.ExecuteNonQuery();
                    con.Close();

                    if (i >= 1)
                        return true;
                    else
                        return false;
                }
            }
        }
        catch (Exception ex)
        {
            string e = ex.Message;
            return false;
        }
    }

    public static T FromXML<T>(string xml)
    {
        using (var stringReader = new StringReader(xml))
        {
            var serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stringReader);
        }
    }

    public string ToXML<T>(T obj)
    {
        using (var stringWriter = new StringWriter(new StringBuilder()))
        {
            var xmlSerializer = new XmlSerializer(typeof(T));
            xmlSerializer.Serialize(stringWriter, obj);
            return stringWriter.ToString();
        }
    }

    private string ConstructXmlFromList(List<string> list)
    {
        return ToXML(list);
    }
}

And again, it's easy to rehydrate the XML fragment into the List<string> that you started with. 同样,很容易将XML片段重新水化为您开始使用的List<string> You'd simply use 您只需使用

var myList = FromXML<List<string>>(fieldValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 选中复选框时,如何将当前 model 详细信息的值传递给 asp.net mvc 中的 controller 操作 - How to pass values of the current model details to controller action in asp.net mvc when checkbox is checked 如何通过使用ASP.NET MVC将复选框作为参数传递给控制器​​功能 - How to pass checkbox checked as a parameter in controller function using ASP.NET MVC 如何在ASP.NET MVC中向控制器正确提交复选框值 - How to correctly submit checkbox values to controller in ASP.NET MVC 将选中的复选框存储在数据库ASP.NET C#的gridview中 - Store checked checkbox in gridview in database ASP.NET C# 如何从asp.net中的多个选中的复选框中获取值? - How to get values from multiple checked checkboxes in asp.net? 在ASP.NET MVC中设置CheckBox的Checked属性 - Setting the Checked property of a CheckBox in ASP.NET MVC 选中复选框时 ASP.NET MVC 更改数据库值 - ASP.NET MVC Change Database value when checkbox is checked 不选中时不绑定checkBox-ASP.NET MVC - dont bind checkBox when not checked - ASP.NET MVC 如何在ASP.Net mvc3 Razor中使用多个Checkbox - how to use multiple Checkbox in ASP.Net mvc3 Razor 如何使用Jquery从Asp.net MVC中的CheckBox中获取选定的值? - How to get the selected values from CheckBox in Asp.net MVC using Jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM