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

在线投票系统中关联问题ID创建答案的技术实现求助

解决关联问题ID创建答案的问题

嘿,我完全懂你现在的困扰——已经搞定了问题的增删改,结果卡在答案和问题的关联上了。别担心,咱们一步步把这个问题捋清楚,很快就能解决~

首先得提个小建议:你现在用Get请求来创建答案其实不太合适哦。Get是用来获取资源的,而创建/修改这种写操作应该用Post请求,这样既符合RESTful规范,也能避免参数暴露在URL里、浏览器缓存这些问题。

接下来咱们一步步实现正确的关联创建逻辑:

1. 确保Answer模型有问题关联字段

首先你的Answer实体需要有一个外键属性来关联Question,这样数据库层面才能建立关联:

public class Answer
{
    public int Id { get; set; }
    public string Text { get; set; }
    // 关联问题的外键
    public int QuestionId { get; set; }
    // 可选:导航属性,方便EF Core加载关联的问题
    public Question Question { get; set; }
}

2. 重构控制器的AddAnswer方法

咱们把Get和Post请求分开:Get用来显示添加答案的页面,Post用来处理实际的创建逻辑。

Get请求(显示页面)

这里接收问题ID,把它传递给视图,方便后续提交时带回:

public ActionResult AddAnswer(int questionId)
{
    // 把问题ID存到ViewBag里,或者用ViewModel传递
    ViewBag.QuestionId = questionId;
    return View();
}

Post请求(处理创建)

这里接收问题ID和答案文本,创建Answer实例时把QuestionId赋值,完成关联:

[HttpPost]
[ValidateAntiForgeryToken] // 防跨站请求伪造,一定要加
public ActionResult AddAnswer(int questionId, string text)
{
    // 先做简单验证:文本不能为空
    if (!string.IsNullOrWhiteSpace(text))
    {
        using (var dbContext = new YourDbContext()) // 替换成你的上下文类
        {
            var newAnswer = new Answer
            {
                Text = text,
                QuestionId = questionId // 核心:把问题ID绑定到答案上
            };
            
            dbContext.Answers.Add(newAnswer);
            dbContext.SaveChanges();
            
            // 创建成功后跳回问题详情页
            return RedirectToAction("Details", "Question", new { id = questionId });
        }
    }
    
    // 如果验证失败,回到页面并保留输入状态
    ViewBag.QuestionId = questionId;
    ViewBag.Text = text;
    return View();
}

3. 视图里传递问题ID

在AddAnswer的视图中,需要把问题ID作为隐藏字段放在表单里,这样提交Post请求时就能自动把ID传给控制器:

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <!-- 隐藏字段:传递问题ID,用户看不到但提交时会带上 -->
    @Html.Hidden("questionId", ViewBag.QuestionId)
    
    <div class="form-group">
        <label>答案内容</label>
        <input type="text" name="text" class="form-control" value="@ViewBag.Text" />
    </div>
    
    <button type="submit" class="btn btn-primary">添加答案</button>
}

进阶:用ViewModel更规范

如果你的参数比较多,或者想做更严谨的验证,推荐用ViewModel来封装参数:

public class AddAnswerViewModel
{
    public int QuestionId { get; set; }
    
    [Required(ErrorMessage = "请输入答案内容")]
    public string Text { get; set; }
}

然后控制器的Post方法改成:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddAnswer(AddAnswerViewModel model)
{
    if (ModelState.IsValid)
    {
        using (var dbContext = new YourDbContext())
        {
            var newAnswer = new Answer
            {
                Text = model.Text,
                QuestionId = model.QuestionId
            };
            
            dbContext.Answers.Add(newAnswer);
            dbContext.SaveChanges();
            
            return RedirectToAction("Details", "Question", new { id = model.QuestionId });
        }
    }
    
    // 验证失败返回视图,保留用户输入
    return View(model);
}

对应的强类型视图:

@model AddAnswerViewModel

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    @Html.HiddenFor(m => m.QuestionId)
    
    <div class="form-group">
        @Html.LabelFor(m => m.Text)
        @Html.TextBoxFor(m => m.Text, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger" })
    </div>
    
    <button type="submit" class="btn btn-primary">添加答案</button>
}

这样一来,你就能顺利通过问题ID关联创建答案啦~核心就是确保Answer实体有外键,创建时给外键赋值,并且在表单中正确传递问题ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:28:33