Radio button list in ASP.NET MVC
When developing web applications , you may need to show radio button list in ASP.NET MVC so that users can make a selection from the options(radio buttons) and submit the form. We can do this easily with the help of MVC Model binding.
Let’s create a quiz page where we are going to show some questions with it’s answers to the user and user can select an answer from the available answer options, represented by radio buttons.
So first we will create some ViewModels for our view. ViewModel is nothing but a POCO class which we will use to transfer data between the action method and the view. So let’s create 3 classes like this.
public class Question
{
public int ID { set; get; }
public string QuestionText { set; get; }
public List<Answer> Answers { set; get; }
public string SelectedAnswer { set; get; }
public Question()
{
Answers = new List<Answer>();
}
}
public class Answer
{
public int ID { set; get; }
public string AnswerText { set; get; }
}
public class Evaluation
{
public List<Question> Questions { set; get; }
public Evaluation()
{
Questions = new List<Question>();
}
}
Now, in our GET action method for the view, we will create an object of our ViewModel (Evaluation) class and set the Questions and it’s Answers properties and then send that to the view by passing it to the View method.
public ActionResult Index()
{
var evalVM = new Evaluation();
//the below is hardcoded for DEMO. you may get the data from some
//other place and set the questions and answers
var q1 = new Question { ID = 1, QuestionText = "What is your favourite language" };
q1.Answers.Add(new Answer { ID = 12, AnswerText = "PHP" });
q1.Answers.Add(new Answer { ID = 13, AnswerText = "ASP.NET" });
q1.Answers.Add(new Answer { ID = 14, AnswerText = "Java" });
evalVM.Questions.Add(q1);
var q2 = new Question { ID = 2, QuestionText = "What is your favourite DB" };
q2.Answers.Add(new Answer { ID = 16, AnswerText = "SQL Server" });
q2.Answers.Add(new Answer { ID = 17, AnswerText = "MyQL" });
q2.Answers.Add(new Answer { ID = 18, AnswerText = "Oracle" });
evalVM.Questions.Add(q2);
return View(evalVM);
}
Now our next step is to create the views to render the UI. We are going to create an editor template to render the questions and it’s answers. So Let’s go to the Views folder and create a folder called EditorTemplates under the current controller folder (if you added the GET action method to Home controller, this will be ~/Views/Home)
After creating the folder, Add a new Editor template to that. Right click on the folder and select Add View option and give the name same as the type name (in this case Question).
Now add the below code to the newly created editor template (Question.cshtml)
@model ViewModels.Question
<div>
@Html.HiddenFor(x=>x.ID)
<h3> @Model.QuestionText </h3>
@foreach (var a in Model.Answers)
{
<p>
@Html.RadioButtonFor(b=>b.SelectedAnswer,a.ID) @a.AnswerText
</p>
}
</div>
What we are doing in the above code is, iterating through each Answers and showing a Radio button and the answer text. We are using the RadioButtonFor html helper method to render the radio button.
Now let’s go to our main view (index.cshtml) and write some code. Our main view will be strongly typed to our Evaluation viewmodel and we will use the EditorFor html helper method to bring our editor template to the main view(index.cshtml).
@model ViewModels.Evaluation
<h2>Quiz 24</h2>
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.Questions)
<input type="submit" />
}
now run the app (hit F5) and you will see the screen with the questions and answers. each answer will be accompanied by a radio button so that user can select one.
Getting the selected radio button values on form post
To get the selected radio button values on form submit, we can check the properties of the posted model. MVC Model binding can bind the posted form data to an instance of our ViewModel. So let’s add the below code to handle the POST action method.
[HttpPost]
public ActionResult Index(Evaluation model)
{
if (ModelState.IsValid)
{
foreach (var q in model.Questions)
{
var qId = q.ID;
var selectedAnswer = q.SelectedAnswer;
// Save the data
}
return RedirectToAction("ThankYou"); //PRG Pattern
}
//to do : reload questions and answers
return View(model);
}
Now if you run the program and use visual studio break points, you can see that the selected radio button values (AnswerID in our case) is available in the SelectedAnswer property of each question.
Hope this helps. You can download the sample source code here. Do not forget to say “Hi” to me, if this post was useful to you.





October 13th, 2012 at 2:04 pm
Very nice explanation! Helped a lot! But could not get the sample to work. I’m getting: “The project type is not supported by this installation.” error.
I’m using VS2010, MVC3, .NET 4.0
Thanks
October 13th, 2012 at 2:44 pm
Andreson : Glad it helped you. The sample code is created in VS2012. That is the reason you can not open it with VS2010.
What you can do is create an empty MVC3 project in VC2010 and copy the code to your relevant files (Home controller , Index view, Editor template and the ViewModels. I have not used any features of MVC4/ dot net 4.5 in the demo. So your code should work fine. Let me know if that works, otherwise i will upload the demo in VS2010.
You can download the trial version of VS2012 here. Let me know if you run into any more problems.
February 6th, 2013 at 11:22 am
Nice post, but was wondering what would happen in the event that the validation failed? I think that Questions.Answers would be null as model wouldn’t have serialised properly?
That’s certainly my experience – specific when you have a foreach in a edit template – and is indeed how I’ve ended up here.
Any ideas how to solve this?
February 25th, 2013 at 12:51 am
Hi Don,
Nice job !
Your post helped me to understand a good way to handle radiobutton rendering using an EditorTemplate.
I like the MVC Model Binding which binds all the posted question/answer html fields back to the View Model Questions list.
BTW, you’re code was NOT working to show REQUIRED field errors when clicking Submit.
Fix was to add the jquery validation scripts ( bundle ) to the view: index.cshtml
@model ViewModels.Evaluation
Quiz 24
@using (Html.BeginForm())
{
@Html.ValidationSummary()
@Html.EditorFor(x=>x.Questions)
}
@section scripts
{
// add unobtrusive jquery validation scripts to page here
@Scripts.Render(“~/bundles/jqueryval”)
}
and question.cshtml editortemplate needs the validationmessagefor helper
@model ViewModels.Question
@Html.HiddenFor(x=>x.ID)
@Model.QuestionText
@foreach (var a in Model.Answers)
{
@Html.RadioButtonFor(b=>b.SelectedAnswer,a.ID) @a.AnswerText
}
@Html.ValidationMessageFor( x => x.SelectedAnswer )
February 28th, 2013 at 7:52 am
Hello,
Thanks for your post, it help me a lot.
I have a question regarding the model, when you click on the submit button, and your model is not valid, you return View(model) but the Evaluation model is empty
You only have SelectedAnswer and ID.
Sorry, maybe it’s a stupid question but i’m really new in ASP.NET MVC
What do we need to do for having the full model in the POST ?
Thank you,
March 1st, 2013 at 9:20 am
Math : Thanks for stopping by. When ModelState.IsValid is false, we are returning the posted model back to the form. It is NOT empty or NULL. But it won’t have the Question Text/Answers there as those were not residing in any form elements (input , hidden elements). So when we post the form first time by clicking the submit button, Those won’t be included in the MVC model binding. If you put a break point and inspect the posted model, you can see those are null. That is y i have a commented line saying “Reload the questions” before returning back to the view. If you want to include those in the posted form data and thus in the model binding process, you may keep those in hidden variables in the form (You can use Html.HiddenFor helper method for this).
March 1st, 2013 at 9:26 am
Paul : Thanks. It will validate even without the client side javascript. Remember that never trust on Client side validation only. Always make sure that you have validation at your server side too.
I made some corrections to the code (changed SelectedAnswer’s data type from int to string) and now it does the validation as well( i tested server side validation). You need to add the ValidationSummary or ValidationMessageFor helper methods to the form as needed.
March 13th, 2013 at 11:44 am
Thank You. This has been very useful however i have a doubt and hope that it would be solved.
I would like to use the similar structure and add questions to the quiz but the answers should not be given via radio button.
The answer should be typed in by user using either textboz or textarea.
And i am really new to the MVC world.
March 13th, 2013 at 12:41 pm
Nikesh : If you want textbox instead of radio button, go to the editor template we created and have textbox there instead of radiobuttons. Use the Html.TextBoxFor html helper method to render textbox. It will work fine. you may remove the foreach loop and keep only one textbox if you need to do so.
March 13th, 2013 at 12:44 pm
Thank You for the suggestion Shyju but the problem is that i need both radiobuttons and textboxes. And the problem is that i m using the same for loop for adding questions and answers.
I would like to randomize the answer field for a certain questions to be radiobutton and some to be textboxes. Any Suggestions where i can modify my existing code or do i need to change the structure totally?
March 13th, 2013 at 12:49 pm
Nikesh : You need to save that ( Which questions has Radio button type answers / Textbox type answers) in your question table or an associated table. And in your GET Action method, when you read the question, read this setting and send that to the view through your viewmodel. (you need to add relevant property in your view model to hold this information). Then in your editor template, check what type of answer this question has, and then show either radio or textbox.
March 13th, 2013 at 12:52 pm
Oh thanks..Will try to implement it and try to get the output.
Thanks in advance.
March 15th, 2013 at 9:32 am
I managed to get the textboxes in by using a simple if condition but now i m having problem for adding the selected answer into the database. Any suggestions how to go about for entering values that are selected by the user into the database ?
March 16th, 2013 at 3:30 pm
You should be able to get the selected items in the posted(bounded by mvc model binding) models properties and then you can easily save that to the database. put a breakpoint in your HttpPost action method and inspect the posted model.
May 21st, 2013 at 10:58 pm
Hi,
I am creating the project in MVC4 and I have two issues.
1) When I have input type = “submit”, form is not posted back. It remains as it is.
2) I am using html.ActionLink to have a postback call but at that time, it is calling the same get method and not the post method.
Any inputs why these issues are creeping in.
May 22nd, 2013 at 1:20 am
@Varun :
#1) Make sure your submit button is inside a form tag.
#2) Html.ActionLink method renders anchor tag which obviously results in an HTTP GET request when user clicks on it. So You should either do any of these
a) Using javascript, listen to the click event of the anchor tag and make jquery post call to the action method.
b) Use the submit button inside the form instead of the anchor tag.