You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC多选框值批量保存到数据库的问题排查

ASP.NET Core MVC复选框仅保存第一个选中值问题

在ASP.NET Core MVC中使用复选框向数据库保存数据时,每次仅能保存一个值;选中多个值时,仅存储第一个选中值。相关代码如下:

ViewModel

public class CreatePostViewModel
{
    // 其他代码
    
    // 分类
    public string? CollectionCategory { get; set; }

    // 分类列表
    public List<CollectionCategoryModel>? CollectionCategoryList { get; set; }
}

Controller

public async Task<IActionResult> CreateAsync()
{
    // 分类列表
    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
        {
            // 其他代码             

            // 分类
            CollectionCategory = postVM.CollectionCategory,
        };

         return RedirectToAction("Index");
    }
    else
    {
        // 错误处理
    }
    return View(postVM);
}

View

<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>

补充问题

Update 1

将Model和ViewModel中的public string? CollectionCategory改为public List<string>? CollectionCategory后,出现错误:JsonReaderException: 'S' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 1.,错误出现在Index控制器第33行。相关代码:

Controller:

[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);
}

ViewModel:

public class CardsViewModel
{
    public List<PostModel>? PostCard { get; set; }
    public List<CollectionModel>? CollectionCard { get; set; }
}

Update 2

补充数据库相关代码:ApplicationDbContext、PostRepository、IPostInterface

Update 3

在ViewModel中使用List<string>?但未在Controller中使用string.Join()时,出现CS0029错误。


内容的提问来源于stack exchange,提问作者ZNAXNOR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 23:27:06