ASP.NET Core MVC 绑定问题

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

我正在尝试开发一个简单的博客应用程序来学习 ASP.NET Core 8 MVC。类别和帖子模型在多对多关系之间链接。当我尝试在多选中编辑类别时,我在 PostController 端看不到任何类别数据。

PostController 编辑发布端点:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Id,Title,Content,CreateAt,IsPublish,Categories")] Post post){
        if (id != post.Id){
            return NotFound();
        }
        
        Console.WriteLine(post.Categories.Count()); // 0 value

        if (ModelState.IsValid){
            try {
                _context.Update(post);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PostExists(post.Id)){
                    return NotFound();
                }
                else{
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(post);
    }

PostController 发布获取端点

// GET: Post/Edit/5
public async Task<IActionResult> Edit(Guid? id){
    if (id == null){
        return NotFound() 
    }

    var post = await _context.Posts.Include(p => p.Categories).FirstOrDefaultAsync(p => p.Id == id);
    ViewBag.Categories = _context.Categories.Select(r=>new SelectListItem {Value=r.Id.ToString(),Text=r.Name}).ToList();

    if (post == null){
        return NotFound();
    } 
    return View(post);
}

帖子编辑页面:

@model BlogApp.Models.Post
<div class="form-group mt-3">
     @foreach(var category in @Model.Categories){
          <span> @category.Name </span>
     } //for print selecting categories...
     <select multiple="multiple" class="form-select" id="multi_select" asp-for="@Model.Categories" asp-items="(List<SelectListItem>)ViewBag.Categories"></select>
</div>
c# asp.net-mvc asp.net-core data-binding
1个回答
0
投票

首先将以下语句添加到帖子模型中:

public class Post
{   
    [NotMapped]
    public List<Guid> SelectedCategoryIds { get; set; }
}

Post Controller 编辑如下:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(Guid id, [Bind("Id,Title,Content,CreateAt,IsPublish,SelectedCategoryIds")] Post post){
    if (id != post.Id){
        return NotFound();
    }
        
    Console.WriteLine(post.SelectedCategoryIds);

    if (ModelState.IsValid){
       try {
            var existingPost = await _context.Posts.Include(p => p.Categories).FirstOrDefaultAsync(p => p.Id == post.Id);
            existingPost.Title = post.Title;
            existingPost.Content = post.Content;
            existingPost.CreateAt = post.CreateAt;
            existingPost.IsPublish = post.IsPublish;

            existingPost.Categories = _context.Categories.Where(c => post.SelectedCategoryIds.Contains(c.Id)).ToList();
            _context.Update(existingPost);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException){
            if (!PostExists(post.Id)){
                return NotFound();
            }
            else{
                throw;
            }
        }
        return RedirectToAction(nameof(Index));
    }
    return View(post);
}

像这样查看页面编辑:

<div class="form-group mt-3">
    @foreach(var category in @Model.Categories){
        <span> @category.Name </span>
    }
    <select multiple="multiple" class="form-select" id="multi_select" asp-for="@Model.SelectedCategoryIds" asp-items="(List<SelectListItem>)ViewBag.Categories"></select>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.