I’m creating an online exam. I want to show the choices for each question in view.when I run the program it has an error “null reference”.
This is my Question table:
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
}
This is my choices table:
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
}
This is my view:
@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>
}
This is the action method:
public IActionResult ShowQuestions(int id)
{
return View(_questionService.GetAllQuestions(id));
}
This is the method:
public List<Question> GetAllQuestions(int examId)
{
return _context.questions
.Where(q => q.ExamId == examId).ToList();
}
I have some choices in my choice table for a question but it doesn’t show them. What should I write in my query?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
When you load your questions from the database, you have to include choiceQuestionSelection otherwise it would not be loaded
_context.Questions.Include(q => q.choiceQuestionSelection).Where(q => q.ExamId == examId);
Also, in case choiceQuestionSelection is empty, you must initialize it as an empty list to prevent a null reference when you call it.
public class Question
{
public Question()
{
choiceQuestionSelection = new List<choiceQuestionSelection>{};
}
public List<ChoiceQuestionSelection> choiceQuestionSelection { get; set; }
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0