在 ASP.NET Core MVC 中将多个复选框值保存到数据库

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

我正在使用复选框将数据保存在数据库中。它一次只能保存一个值。当选择多个值时,它只存储第一个选择的值。

我已经用谷歌搜索了我的问题。多种解决方案建议在模型中使用

List<string> Name
。我尝试这样做,但我的控制器给了我错误CS0029


  • 数据库表(集合类别):
身份证 类别名称
1 第一类
2 第二类
... ...

代码-

  • 型号:
public class PostModel
{
    // Code before

    public string? CollectionCategory { get; set; }
}
public class CollectionCategoryModel
{
    [Key]
    public int Id { get; set; }
    public string CategoryName { get; set; }
}
  • 视图模型:
public class CreatePostViewModel
{
    // Code before
    
    // Category
    public string? CollectionCategory { get; set; }

    // Category List
    public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}
  • 控制器:
public async Task<IActionResult> CreateAsync()
{
    // Category List
    var CreatePostCategoryVM = new CreatePostViewModel
    {
        CollectionCategoryList = await _context.CollectionCategories.ToListAsync()
    };

    return View(CreatePostCategoryVM);
}

[HttpPost]
public async Task<IActionResult> Create(CreatePostViewModel postVM)
{
    if (ModelState.IsValid)
    {
        var post = new PostModel
        {
            // Code before             

            // Category
            CollectionCategory = postVM.CollectionCategory,
        };

         return RedirectToAction("Index");
    }
    else
    {
        // Error
    }
    return View(postVM);
}

错误:

(JsonReaderException:“S”是值的无效开头。LineNumber:0 | BytePositionInLine:1。)

[HttpGet]
public async Task<IActionResult> Index()
{
    var CardPostVM = new CardsViewModel
    {
        PostCard = await _context.Posts.ToListAsync()
    };

    var cached = _cache.TryGetValue("post", out var post);
    if (cached)
    {
        return View(post);
    }

    return View(CardPostVM);
}
  • 查看:
<div class="form-check">
    @foreach (var list in Model.CollectionCategoryList)
    {
        <input type="checkbox" asp-for="CollectionCategory" id="@list.CategoryName" value="@list.CategoryName">
        <label asp-for="CollectionCategory" for="@list.CategoryName"> @list.CategoryName </label>
    }
</div>

谢谢你

c# html checkbox asp.net-core-mvc
1个回答
0
投票

您的模型设置为仅捕获

CollectionCategory
的单个字符串值。将
CollectionCategory
中的
PostModel
更改为
List<string>
以存储多个选定的类别。

public class PostModel
{
    // Other properties before

    public List<string>? CollectionCategories { get; set; }
}

更新

CreatePostViewModel
以使用
List<string>
代替
CollectionCategory

public class CreatePostViewModel
{
    // Other properties before

    // Category
    public List<string>? CollectionCategory { get; set; }

    // Category List
    public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.