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

ASP.NET中表单值无法传递到控制器Post方法的问题

问题原因及解决方案

核心原因:模型绑定字段不匹配

你的视图使用BlogViewModel作为模型,表单中通过asp-for="addComment.UserId"生成的输入字段name属性会带上addComment.前缀(比如实际提交的字段名是addComment.UserId或addComment_UserId)。但Post方法的参数是AddCommentViewModel commentModel,ASP.NET的模型绑定器会尝试匹配不带前缀的字段名(如UserId、Content),两者无法对应,导致commentModel的所有属性值为null或0。

解决方法

方法一:修改Post方法参数为BlogViewModel

直接接收视图使用的模型类型,从模型中提取评论数据:

[HttpPost]
public IActionResult ViewBlog(BlogViewModel model)
{
    if (ModelState.IsValid)
    {
        var comment = new Comment
        {
            Content = model.addComment.Content,
            CreatedAt = DateTime.Now,
            UserId = model.addComment.UserId,
            BlogId = model.addComment.BlogId,
        };
        _db.Comments.Add(comment);
        _db.SaveChanges();
    }

    // 重新获取博客及评论数据,避免视图无数据报错
    var blogViewModel = new BlogViewModel
    {
        blog = _db.Blogs.Include(b => b.User)
                        .Include(b => b.Comments)
                        .FirstOrDefault(u => u.Id == model.addComment.BlogId),
        addComment = new AddCommentViewModel()
    };
    return View(blogViewModel);
}

方法二:给Post参数添加绑定前缀特性

通过[Bind(Prefix = "addComment")]告诉模型绑定器字段的前缀,匹配表单提交的带前缀字段:

[HttpPost]
public IActionResult ViewBlog([Bind(Prefix = "addComment")] AddCommentViewModel commentModel)
{
    if (ModelState.IsValid)
    {
        var comment = new Comment
        {
            Content = commentModel.Content,
            CreatedAt = DateTime.Now,
            UserId = commentModel.UserId,
            BlogId = commentModel.BlogId,
        };
        _db.Comments.Add(comment);
        _db.SaveChanges();
    }

    // 重新获取博客数据返回视图
    var blogViewModel = new BlogViewModel
    {
        blog = _db.Blogs.Include(b => b.User)
                        .Include(b => b.Comments)
                        .FirstOrDefault(u => u.Id == commentModel.BlogId),
        addComment = new AddCommentViewModel()
    };
    return View(blogViewModel);
}

额外注意事项

  • Post方法返回视图时,必须重新构建BlogViewModel并传递,否则视图会因缺少模型数据报错。
  • 确保AddCommentViewModel的所有属性都是public且包含get/set方法,这是模型绑定的前提。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 07:14:52