I'm programming a web app (in mvc) where a 'quizmaster' can add questions. A quiz contains 3 questions.
I would like to achieve that the quizmaster can add both 3 questions on the same page/form.
The problem is that I only know how to submit one question and not three of them.
So I created a view (AddQuestions), two models (Question and Quiz) and a controller (QuizController).
The view is strongly typed with the Question model. On this view I have a form. At the moment I have a for loop that loops till three, so that 3 questions can be filled in. They are all in one form.
Model
public class Question
{
public int Id { get; set; }
public string Question { get; set; }
public double Points { get; set; }
}
The Quiz class contains an Id, Date and fields to save the Id's of the three questions
View
<form asp-action="AddQuestions" method="post">
@{
for (var i = 0; i < 3; i++)
{
if (i == 0)
{
<span>Question 1</span>
}
else if (i == 1)
{
<span>Question 2</span>
}
else if (i == 2)
{
<span>Question 3</span>
}
<p>
<label asp-for="Question[i]">Question</label>
<input asp-for="Question[i]" />
</p>
<p>
<label asp-for="Answer[i]">Answer</label>
<input asp-for="Answer[i]" />
</p>
<p>
<label asp-for="Points[i]">Points</label>
<input asp-for="Points[i]" />
</p>
}
}
<button type="submit">Add</button>
</form>
Controller
[HttpPost]
public ViewResult AddQuestions(IEnumerable<Question> questionList)
{
return View();
}
I expect the output of questionList is a list of Questions (so I can add these question to the Quiz), but there is no output, because there occured two (the same) errors in the view.
The error is:
"Cannot apply indexing with [] to an expression of type 'double'" This error references to the asp-for="Points[i]" parts.
How can I achieve that the quizmaster can fill in three questions (of the model Question) (for one quiz) at the same page?