Hi svibuk,
Check this example. Now please take its reference and correct your code.
Model
QuestionModel
public class QuestionModel
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public string RadioOrCheck { get; set; }
public List<AnswerModel> Answer { get; set; }
}
AnswerModel
public class AnswerModel
{
public int AnswerId { get; set; }
public string Text { get; set; }
}
Controller
public class HomeController : Controller
{
static int QuestionId = 1;
// GET: Home
public ActionResult Index()
{
return View(PopulateQuestionAnswers(QuestionId));
}
[HttpPost]
public ActionResult Index(string nextPrevious)
{
if (nextPrevious.ToLower() == "next")
{
QuestionId++;
}
else
{
QuestionId--;
}
return View(PopulateQuestionAnswers(QuestionId));
}
public List<QuestionModel> PopulateQuestionAnswers(int? questionId)
{
TestEntities entity = new TestEntities();
List<QuestionModel> questionAnswers = entity.QuizQuestionaries
.Where(x => x.QuestionID == questionId)
.Select(question => new QuestionModel
{
QuestionId = question.QuestionID,
QuestionText = question.Text,
RadioOrCheck = question.Radioorcheck,
Answer = entity.Answers
.Where(x => x.QuestionID == question.QuestionID)
.Select(answer => new AnswerModel
{
AnswerId = answer.AID,
Text = answer.Text
}).ToList()
}).ToList();
return questionAnswers;
}
}
View
@model IEnumerable<_111680_Matrix_Quiz.Models.QuestionModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h4>
Question Answer
</h4>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table class="table">
@foreach (var question in Model)
{
<tr>
<th colspan="2">
@Html.HiddenFor(x => question.QuestionId)
@Html.DisplayFor(x => question.QuestionText)
</th>
</tr>
foreach (var answer in question.Answer)
{
<tr>
<td>
@Html.HiddenFor(x => answer.AnswerId)
@Html.DisplayFor(x => answer.Text)
</td>
<td>
@if (@question.RadioOrCheck.ToLower() == "r")
{
@Html.RadioButton("answer", answer.AnswerId)
}
else
{
@Html.CheckBox("answer", answer.AnswerId)
}
</td>
</tr>
}
}
</table>
<br />
<input id="btnPrevious" type="submit" value="Previous" name="nextPrevious" />
<input id="btnNext" type="submit" value="Next" name="nextPrevious" />
}
</body>
</html>
Screenshot
