I have a list with model objects that i send to a view from the controller, see code below:
[HttpGet]
public IActionResult PlayingQuiz()
{
string category = HttpContext.Session.GetString("selection");
Debug.WriteLine(category);
Parser p = new Parser(category);
List<Question> quizQuestions = new List<Question>();
quizQuestions.Clear();
quizQuestions = p.getQuestionList();
return View(quizQuestions);
}
In the View, a for each loop presents some values from the model objects. And what i am trying to do is to update the model objects, and then return it back to the controller. So a updated List<Questions>
with the value PlayerAnswer
is set, gets to the [HttpsPost] in the controller. See View below:
<div class="row">
<div class="col-lg-12">
<form asp-action="PlayingQuiz">
@foreach (SuperQuiz1.Models.Question q in Model)
{
<h6>@Html.DisplayFor(modelItem => q.Question_)</h6>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary">
<input asp-for=@q.playersAnswer type="radio" value=@Html.DisplayFor(modelItem => q.correct_answer)> @Html.DisplayFor(modelItem => q.correct_answer)
<span asp-validation-for=@q.playersAnswer class="text-danger"></span>
</label>
<label class="btn btn-primary">
<input asp-for=@q.playersAnswer type="radio" value=@Html.DisplayFor(modelItem => q.incorrect_answers[1])> @Html.DisplayFor(modelItem => q.incorrect_answers[1])
<span asp-validation-for=@q.playersAnswer class="text-danger"></span>
</label>
<label class="btn btn-primary">
<input asp-for=@q.playersAnswer type="radio" value=@Html.DisplayFor(modelItem => q.incorrect_answers[3])> @Html.DisplayFor(modelItem => q.incorrect_answers[3])
<span asp-validation-for=@q.playersAnswer class="text-danger"></span>
</label>
<label class="btn btn-primary">
<input asp-for=@q.playersAnswer type="radio" value=@Html.DisplayFor(modelItem => q.incorrect_answers[5])> @Html.DisplayFor(modelItem => q.incorrect_answers[5])
<span asp-validation-for=@q.playersAnswer class="text-danger"></span>
</label>
</div>
}
<div asp-validation-summary="ModelOnly"></div>
<div class="form-group">
<input type="submit" value="Submit answers" class="btn btn-primary" />
</div>
</form>
</div>
And finally the HttpPost action in the conroller, where i wanna receive the list:
[HttpPost]
public IActionResult PlayingQuiz(List<Question> updatedQuestions)
{
Debug.WriteLine("--------------------------------------------");
Debug.WriteLine("SIZE: ", updatedQuestions.Count);
Debug.WriteLine(updatedQuestions[0].Question_);
Debug.WriteLine(updatedQuestions[0].playersAnswer);
return View("TotalScore");
}
The problem was that i used a foreach loop and needed o use a for loop instead. Got this link were i found the solution.