Вот рабочая демонстрация:
1.Модель:
public class CandidateExam
{
public int Id { get; set; }
public string OptionSelected { get; set; }
}
public class QuestionAndAnswers
{
public int Id { get; set; }
public string Question { get; set; }
public string OptionOne { get; set; }
public string OptionTwo { get; set; }
public string OptionThree { get; set; }
public string OptionFour { get; set; }
}
2.Просмотр (Обратите внимание, что вы установили optionOne
с неправильным значением @item.OptionTwo
):
@model IEnumerable<QuestionAndAnswers>
@{
int count = 0;
int i = 0;
}
<form method="post">
@foreach (var item in Model)
{
count = count + 1;
<table class="table" style="background-color:lavender">
<tbody>
<tr class="border-light"><td>Question @count : @item.Question</td></tr>
<tr class="bg-light"><td>Options : </td></tr>
<tr class="border-light"><td><input asp-for="@item.OptionOne" type="radio" name="counter[@i]" value="@item.OptionOne" /> a) @item.OptionOne</td></tr>
<tr class="bg-light"><td><input asp-for="@item.OptionTwo" type="radio" name="counter[@i]" value="@item.OptionTwo" /> b) @item.OptionTwo</td></tr>
<tr class="border-light"><td><input asp-for="@item.OptionThree" type="radio" name="counter[@i]" value="@item.OptionThree" /> c) @item.OptionThree</td></tr>
<tr class="bg-light"><td><input asp-for="@item.OptionFour" type="radio" name="counter[@i]" value="@item.OptionFour" /> d) @item.OptionFour</td></tr>
</tbody>
</table>
i++;
<br />
}
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</form>
3. Контроллер:
public class QuestionAndAnswersController : Controller
{
private readonly YourContext _context;
public QuestionAndAnswersController(YourContext context)
{
_context = context;
}
// GET: QuestionAndAnswers
public async Task<IActionResult> Index()
{
return View(await _context.QuestionAndAnswers.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> Index(string[] counter)
{
foreach(var item in counter)
{
var data = new CandidateExam()
{
OptionSelected = item
};
_context.Add(data);
await _context.SaveChangesAsync();
}
//do your stuff...
}
4.Результат: