I am developing a page for rating questions.
In the view, I have a list of questions and 5 radio buttons in front of each one of them.
<input name="evalId" type="hidden" value="@Model.Evaluation.EvalId" />
foreach (var question in questionList)
{
<input name="questionId" type="hidden" value="@question.QuestionId" />
<div class="row_star" style="border-bottom : 0 none; background: none;">
@if (!String.IsNullOrEmpty(question.QuestionTitre))
{
<p>@question.QuestionTitre.TrimEnd()</p>
}
@* here goes the code for 5 radio buttons*@
}
Now, in my controller I want to be able to know which radio button was checked for each question.
How can I do that ?
Here is my ViewModel
public class EvaluationViewModel
{
/// <summary>
///
/// </summary>
public EvalEvaluation Evaluation
{
get;
set;
}
/// <summary>
///
/// </summary>
public Dictionary<EvalQuizz, List<EvalQuestion>> EvalQuizzQuestionList
{
get;
set;
}
}
Assuming your ViewModel is like this
And in your GET action method, you will return the viewmodel back to the view with some questions and answers filled in it. In the code below I've hardcoded the questions and answers. You may get it from your Repositary/Service layer.
Now we will create an Editor Template to render our Question. so go to your View Folder and create a folder called EditorTemplates under the folder with your current controller name. Add a view to the EditorTemplates folder and give the same name as the class name we want to represent. ie :
Question.cshtml
Now put this code in the editor tempalte
Now go to our main view and use EditorTemplate html helper method to bring the EditorTemplate we created to the main view.
Now in your HttpPost you can check the posted model and get the selected radio button (SelectedAnswer) value there
If you use visual studio breakpoints, you can see the values posted. Thanks to MVC Model binding :)
You can read about it and download a working sample here.