【发布时间】: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