【问题标题】:How to show choices of the question in view using ASP.NET Core?如何使用 ASP.NET Core 在视图中显示问题的选择?
【发布时间】:2021-02-06 11:05:57
【问题描述】:

我正在创建一个在线考试。我想在视图中显示每个问题的选择。当我运行程序时,它有一个错误“空引用”。

这是我的Question 表:

public class Question
{
    [Key]
    public int QuestionId { get; set; }//1
    public int ExamId { get; set; }
    public string UserId { get; set; }
    public string QuestionTitle { get; set; }
    public decimal Grade { get; set; }

    #region relations
    [ForeignKey("UserId")]
    public virtual IdentityUser IdentityUser { get; set; }
    public Exam exam { get; set; }
    public List<ChoiceQuestionSelection> choiceQuestionSelection { get; set; }
    #endregion
}

这是我的选择表:

public class ChoiceQuestionSelection
{
    [Key]
    public int ChoiceQuestionSelectionId { get; set; }
    public int QuestionId { get; set; }
    public string Choice { get; set; }
    public bool IsTrue { get; set; }
    public string FeedbackTrue { get; set; }
    public string FeedbackFalse { get; set; }

    #region relations
    public Question question { get; set; }
    #endregion
}

这是我的看法:

@foreach (var item in Model)
{
    <div class="col-lg-6">
        <div class="well well-lg">
            <h4>@item.QuestionTitle</h4>
            <h6>@item.Grade </h6>
            <p>
            @if (item.choiceQuestionSelection.Any(q => q.QuestionId == item.QuestionId))
            {
                @foreach (var choice in item.choiceQuestionSelection)
                {
                    <label>
                        <input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" 
                     checked="">@choice.Choice
                    </label>
                }
            }
        </p>
    </div>
</div>
}

这是动作方法:

public IActionResult ShowQuestions(int id)
{
    return View(_questionService.GetAllQuestions(id));
}

这是方法:

public List<Question> GetAllQuestions(int examId)
{
    return _context.questions
                   .Where(q => q.ExamId == examId).ToList();
}

我的选择表中有一些问题可供选择,但没有显示出来。我应该在查询中写什么?

【问题讨论】:

  • 你能发布加载数据并将其发送到视图的操作方法吗?这些是可能的原因,首先您没有在查询中包含choiceQuestionSelection,并且由于您没有将choiceQuestionSelection 初始化为空列表,因此您会得到一个空引用
  • 我更新了我的帖子。是的,谢谢。我应该尝试这种方式。我没有包括选择表。

标签: asp.net asp.net-core entity-framework-core


【解决方案1】:

当你从数据库加载你的问题时,你必须包含choiceQuestionSelection否则它不会被加载

_context.Questions.Include(q => q.choiceQuestionSelection).Where(q => q.ExamId == examId);

另外,如果choiceQuestionSelection为空,则必须将其初始化为空列表,以防止调用时出现空引用。

public class Question 
{
    public Question()
    {
        choiceQuestionSelection = new List<choiceQuestionSelection>{};
    }
    public List<ChoiceQuestionSelection> choiceQuestionSelection { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 2022-01-08
    • 2015-04-30
    • 2020-04-13
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多