【发布时间】:2021-04-11 19:40:57
【问题描述】:
我是 Razor 新手,在尝试遍历对象列表时遇到此错误。
这是我的观点:
@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>
这是.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;
}
}
}
这里是服务
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"
},
};
}
}
我尝试初始化评论中的列表,但它也没有工作:(
谢谢!
【问题讨论】:
-
我的回答有用吗?
标签: asp.net-core razor razor-pages