How to store List<string> with checkboxes in Db with Entity framework

问题描述 投票:0回答:1

我对 Asp.net 很陌生

尝试通过做小项目来学习。

我有问题(我卡住了),我想将多个值(由复选框提供)存储到单个数据库表字段中。但无法绕过如何正确地做到这一点。

我要保存数据的类

public class Supplier
    {
        public Guid Id { get; set; }
        public string SupplierName { get; set; }
        public string SupplierAddress { get; set; } 
        public string SupplierOrigin { get; set; }
        public string SupplierGroup { get; set; }
        public  string FustTypeList { get; set; }
    }

我要保存哪一类

 public class FustType
    {
        public Guid Id { get; set; }
        public string FustTypeName { get; set; }
        public string? Comment { get; set; } = "N/A";
        public bool IsChecked { get;set; }
    }

Controller(与form和view相关的方法)

        [HttpGet]
        public async Task<IActionResult> CreateSupplier()
        {

            List<CheckBoxModel> checkBoxModels = new List<CheckBoxModel>();
            List<string> fustTypeList = new();
            await applicationDbContext.FustTypes.ForEachAsync(item => { fustTypeList.Add(item.FustTypeName); });
            int fustTypes = 0;
            await applicationDbContext.FustTypes.ForEachAsync(item =>
            {
                checkBoxModels.Add(
                        new CheckBoxModel()
                        {
                            Id= fustTypes+1,
                            CheckoxName=item.FustTypeName,
                            IsChecked=false
                        });
            });

            ViewBag.FustTypes = fustTypeList;
            ViewBag.CheckBoxModels = checkBoxModels;
            List<string> originList = new();
            await applicationDbContext.Origins.ForEachAsync(item => { originList.Add(item.OriginName); });
            ViewBag.Origins = originList;
            List<string> groupList = new();
            await applicationDbContext.Groups.ForEachAsync(item => { groupList.Add(item.GroupName); });
            ViewBag.Groups = groupList;

            return View();
        }

[HttpPost]
        public async Task<IActionResult> Add(Supplier addSupplierRequest, string Save, List<CheckBoxModel> checkboxModelList)
        {
            if (Save != null)
            {
                var supplier = new Supplier()
                {
                    Id = Guid.NewGuid(),
                    SupplierName = addSupplierRequest.SupplierName,
                    SupplierAddress = addSupplierRequest.SupplierAddress,
                    FustTypeList = addSupplierRequest.FustTypeList,
                    SupplierGroup = addSupplierRequest.SupplierGroup,
                    SupplierOrigin = addSupplierRequest.SupplierOrigin
                };
                await applicationDbContext.Suppliers.AddAsync(supplier);
                await applicationDbContext.SaveChangesAsync();


                TempData["result"] = "Success";
                TempData["action"] = "Supplier Creation";
                return RedirectToAction("Index");
            }
            else
            {
                TempData["result"] = "Fail";
                TempData["action"] = "Supplier Creation";
                return RedirectToAction("CreateSupplier");
            }
        }

查看提交表单的文件(原始视图更大,包含不同的信息,但为了保持紧凑我删除了它,因为表单正在正确提交其他数据并将数据存储在数据库中)

@model FustWebApp.Models.Domain.Supplier
@using FustWebApp.Models;
@{
    ViewData["Title"] = "Create Supplier";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";

    var checkboxList = (List<CheckBoxModel>)ViewBag.CheckBoxModels;

}
@if (@ViewBag.Message != null)
{
    <div class="@ViewBag.Style  text-sm-center mb-1 py-1"><h4>@ViewBag.Message</h4></div>
}

@using (@Html.BeginForm("Add", "Suppliers", HttpMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="container">

        <div class="row mb-2">
            
            @for (int i=0;i<@checkboxList.Count();i++)
            {
                 @Html.LabelFor(model=>model.FustTypeList,htmlAttributes:new{@class ="col-form-label col-sm-2"})
                <div class="col-auto">

                    @Html.CheckBoxFor(model=>model.FustTypeList)

                    @Html.ValidationMessageFor(model => model.FustTypeList, "", new { @class = "text-danger" })

                </div>
            
            }

        </div>

    </div>

}

复选框是根据不同数据库表中已保存的数据生成的。 想法是,基于什么复选框被“选中”,它被添加到带有 FustTypeName 的列表列表中 我卡在了一部分

 @Html.CheckBoxFor(model=>model.FustTypeList)

因为我的列表应该包含字符串,但是复选框的输出是布尔值

是否有更好的选择如何将多个“复选框”值存储到单个数据库字段中?

我尝试将复选框输出存储在单个字符串中,但没有达到预期效果。因为我不知道如何传回控制器选择的选项。试过

<Input type="checkbox" name="Checked" value="CheckboxName"/>

在控制器中得到

List<string>Checked{get;set;}

哪个应该存储所有值,但它在表单提交时始终为空字段

c# asp.net-mvc entity-framework razor-pages
1个回答
0
投票

我采用了不同的方法,现在可以通过使用分隔符 ',' 将项目名称作为单个字符串存储在数据库字段中

在视图中我改为下面

<div class="row mb-2">
        
        @for (int i=0;i<@checkboxList.Count();i++)
        {
            
            <div class="col-auto">

                <input name="AreChecked" type="checkbox" value="@checkboxList[i].CheckBoxName" /> @checkboxList[i].CheckBoxName<br />
                

                @Html.ValidationMessageFor(model => model.FustTypeList, "", new { @class = "text-danger" })


            </div>
        
        }

    </div>

控制器:

    [BindProperty]
    public List<string> AreChecked { get; set; }
public async Task<IActionResult> Add(Supplier addSupplierRequest, string Save, List<string> AreChecked)
    {

        if (Save != null)
        {

            string fustTypeList = string.Join(",", AreChecked);

            var supplier = new Supplier()
            {
                Id = Guid.NewGuid(),
                SupplierName = addSupplierRequest.SupplierName,
                SupplierAddress = addSupplierRequest.SupplierAddress,
                FustTypeList = fustTypeList,
                SupplierGroup = addSupplierRequest.SupplierGroup,
                SupplierOrigin = addSupplierRequest.SupplierOrigin
            };

并且通过查看输入的值来重新生成在视图中选中了哪些复选框,我将它们处理为:

@for (int i = 0; i < checkboxList.Count; i++)
        {
            <div class="col-auto">
                @if (Model.FustTypeList.Split(',').Contains(checkboxList[i].CheckBoxName))
                {
                    <input name="AreChecked" type="checkbox" checked="checked" />
                    @checkboxList[i].CheckBoxName

                    <br />
                    @Html.ValidationMessageFor(model => model.FustTypeList, "", new { @class = "text-danger" })
                }
                else
                {
                    <input name="AreChecked" type="checkbox" value="@checkboxList[i].CheckBoxName" />
                    @checkboxList[i].CheckBoxName

                    <br />
                    @Html.ValidationMessageFor(model => model.FustTypeList, "", new { @class = "text-danger" })
                }
            </div>
        }

不确定这是否是最好的方法,但它可以完成工作。 我能够将多个选择存储在单个字符串中,并在视图中重新生成值。

仍在学习 Asp.net 和 Entity Framework,所以我还不太了解关系

© www.soinside.com 2019 - 2024. All rights reserved.