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

提交BlogComment表单时RefId无效值为空的问题求助

解决Blog评论提交时"RefId无效,尝试值为空"的问题

问题根源

你的RefId是BlogComment模型的主键,类型为非可空int,但前端表单里的RefId输入框未赋值,提交时传递空值触发模型验证失败。而且主键本该由数据库自动生成,完全不需要前端传递。

具体修复步骤

1. 配置主键自增

在BlogComment模型的RefId属性上添加自增特性,让数据库自动生成主键值:

/// <summary>
/// Referans Numarası
/// </summary>
[Key]
[Column(TypeName = "int")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] // 添加该行开启自增
public int RefId { get; set; }

2. 删除前端无用的RefId输入框

既然不需要前端传递主键,直接移除表单里的RefId输入项:

<!-- 删除这一行 -->
<input name="RefId" id="RefId" type="number" hidden>

3. 调整控制器的绑定字段

控制器Create方法的Bind列表里去掉RefId,因为这个值由数据库生成,不需要接收前端参数:

public async Task<IActionResult> Create([Bind("BlogId,BlogCommentApproved,BlogCommentApprovedById,BlogCommentApproveDate,CommentCreateDate,Fullname,Email,CommentContent")] BlogComment blogComment)
{
    // 自动填充评论创建时间,无需前端传递
    blogComment.CommentCreateDate = DateTime.Now;
    // 默认设置评论为未审核状态
    blogComment.BlogCommentApproved = false;

    if (ModelState.IsValid)
    {
        _context.Add(blogComment);
        await _context.SaveChangesAsync();
        // 提交后跳回原博客详情页,而非默认Index
        return RedirectToAction("Details", "Blogs", new { id = blogComment.BlogId });
    }
    ViewData["BlogId"] = new SelectList(_context.Blogs, "RefId", "RefId", blogComment.BlogId);
    return View(blogComment);
}

4. 给BlogId赋值

当前表单里的BlogId输入框是空的,需要将当前博客的ID赋值给它。可以在博客详情视图里通过模型传递:

<!-- 从当前博客模型中获取RefId赋值给BlogId -->
<input name="BlogId" id="BlogId" type="number" hidden value="@Model.RefId">

5. 修正外键特性错误

模型里BlogCommentApprovedById对应的外键特性写错了,需要修正:

/// <summary>
/// Yorumu Onaylayan Kullanıcı Id'si
/// </summary>
public int? BlogCommentApprovedById { get; set; }
[ForeignKey("BlogCommentApprovedById")] // 修正为正确的外键字段名
public virtual User ApprovedBy { get; set; }

6. 清理不必要的隐藏字段

BlogCommentApprovedById、BlogCommentApproveDate这些字段属于后台审核逻辑,用户提交评论时不需要传递,可直接从表单中移除,后续审核时再处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 20:31:04