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

在线投票应用无法展示答案得票数问题求助

嘿,我瞅了瞅你代码里的问题,主要是模型关联、控制器查询逻辑和视图渲染这几块出了问题,咱们一步步来搞定:

1. 先修正模型的关联关系

你的投票模型关系有点混乱,投票应该是绑定到具体答案,答案再绑定到问题。我调整了模型,让EF能正确识别一对多的关联:

public class Answer {
    public int Id { get; set; }
    public string Text { get; set; }
    public int QuestionId { get; set; }
    // 新增关联问题的导航属性
    public virtual Question Question { get; set; }
    public virtual List<Vote> Votes { get; set; }

    public Answer() {
        Votes = new List<Vote>();
    }
}

public class Question {
    public Question() {
        Answers = new List<Answer>();
    }
    public int Id { get; set; }
    public string Text { get; set; }
    public virtual List<Answer> Answers { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public Boolean Active { get; set; }
    // 去掉多余的SelectedAnswer字段,投票结果通过Votes统计即可
}

public class Vote {
    public int Id { get; set; }
    public string IpAdress { get; set; }
    public DateTime VoteDate { get; set; }
    public int AnswerId { get; set; }
    // 新增关联答案的导航属性
    public virtual Answer Answer { get; set; }

    public Vote() {
        // 删掉多余的Questions列表,投票不需要关联多个问题
    }
}

2. 修复控制器的Results方法

原来的控制器逻辑有不少错误,比如Single(q => q.Id == q.Id)会直接返回第一个问题,完全不符合需求。我重新写了逻辑,能正确获取指定问题的所有答案及对应得票数:

public async Task<ActionResult> Results(int questionId) {
    using (var poolDbContext = new PoolContext()) {
        // 获取指定ID的问题,同时加载关联的答案和每个答案的投票记录
        var targetQuestion = await poolDbContext.Questions
            .Include(q => q.Answers)
            .ThenInclude(a => a.Votes) // 嵌套加载每个答案的投票
            .AsNoTracking()
            .SingleOrDefaultAsync(q => q.Id == questionId);

        if (targetQuestion == null) {
            return NotFound(); // 找不到对应问题就返回404
        }

        return View(targetQuestion); // 把问题模型传递给视图
    }
}

3. 修正视图代码

现在视图的模型改成Question,这样就能遍历它的所有答案,展示每个答案的文本和得票数了:

@model PoolManager.Models.Question
@{
    ViewData["Title"] = "投票结果";
}

<h2>@Model.Text 的投票结果</h2>

<div>
    <dl class="dl-horizontal">
        @foreach (var answer in Model.Answers) {
            <dt>@answer.Text</dt>
            <dd>得票数:@answer.Votes.Count</dd>
            <hr />
        }
    </dl>
</div>

<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">编辑问题</a> |
    <a asp-action="Index">返回列表</a>
</div>

额外小提醒

  • 投票的时候记得加IP校验,用IpAdress字段防止同一IP重复投票,这部分可以在投票提交的Action里加判断。
  • 如果项目规模不小,建议用依赖注入管理DbContext,比直接在using里new更规范。

内容的提问来源于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.28 04:09:46