I'm new to Razor and I'm getting this error when trying to loop through a list of objects.
This is my View:
@page
@model QuizModel
@{
ViewData["Title"] = "Quiz Page";
}
<div class="text-center">
<h1 class="display-4">Thanks for checking my first website out, @Model.Visitor.Name. Are you ready?</h1>
<p>Let's see how much you know about me.</a>.</p>
</div>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<form method="post">
@foreach (var question in @Model.QuestionList)
{
<label>@question.Query</label>
}
<button type="submit">Send</button>
</form>
</div>
This is the .cs
namespace myquiz.Pages
{
public class QuizModel : PageModel
{
[ViewData]
[BindProperty]
public string Name { get; set; }
[BindProperty]
public Visitor Visitor { get; set; }
public List<Question> QuestionList { get; set; }
public void OnGet()
{
var quizService = new QuizService();
///QuestionList = new List<Question>();
QuestionList = quizService.GetQuestions();
}
public void OnPost()
{
Name = Visitor.Name;
}
}
}
Here's the service
public class QuizService
{
public List<Question> GetQuestions()
{
return new List<Question>()
{
new Question()
{
Id=1,
Query = "What's my favourite band?",
Option1 = "Beatles",
Option2 = "Rolling Stones",
Option3 = "Led Zeppelin",
Answer = "Led Zeppelin"
},
new Question()
{
Id=2,
Query = "What's my favourite colour?",
Option1 = "Pink",
Option2 = "Yellow",
Option3 = "Maroon",
Answer = "Pink"
},
};
}
}
I tried to initialise the list in the comment but It did't work either :(
Thanks!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…