Home » x Other Posts » Complex model binding for radio buttons in ASP.NET MVC page with Razor

Complex model binding for radio buttons in ASP.NET MVC page with Razor

Let’s say you have an ASP.NET MVC page with four radio buttons. You select one of them and click a Submit button. Form is posted. However, you don’t see the submitted values in the code. Binding between HTML inputs and Post method doesn’t seem to be working.

Complex model binding for radio buttons
Example of a complex model binding for radio buttons

Online sources like this one helps for simple binding but for a complex binding scenario like the one above, please feel free to leverage the sample code below.

Example of complex model binding for radio buttons


<form method="post">
	<div class="container">

	<input type="hidden" asp-for="QuestionViewModel.IsSingleSelection" value="@Model.QuestionViewModel.IsSingleSelection" />
	<input type="hidden" asp-for="QuestionViewModel.ExamQuestionOrder" value="@Model.QuestionViewModel.ExamQuestionOrder" />
	<input type="hidden" asp-for="QuestionViewModel.QuestionId" value="@Model.QuestionViewModel.QuestionId" />
	<p>Select the correct option.</p>
	@for (var i = 0; i < Model.QuestionViewModel.Options.Count(); i++)
		<input type="hidden" asp-for="QuestionViewModel.Options[i].OptionText" value="@Model.QuestionViewModel.Options[i].OptionText" />
		<input type="hidden" asp-for="QuestionViewModel.Options[i].OptionId" value="@Model.QuestionViewModel.Options[i].OptionId" />
		<input type="hidden" asp-for="QuestionViewModel.Options[i].IsCorrect" value="@Model.QuestionViewModel.Options[i].IsCorrect" />
		<input type="radio" asp-for="SelectedOptionId" value="@Model.QuestionViewModel.Options[i].OptionId" />
		<label for=" @Model.QuestionViewModel.Options[i].OptionText">&nbsp;&nbsp;  @Model.QuestionViewModel.Options[i].OptionText </label> <br />
	<button type="submit" asp-route-questionIndex="@(Model.QuestionNdx + 1)" class="btn btn-primary @nextDisabled">Next</button>



namespace Test.WebUI.ViewModels
    public class QuestionViewModel
        public int QuestionId { get; set; }

        public int ExamQuestionOrder { get; set; }

        public string QuestionText { get; set; }

        public bool? IsSingleSelection { get; set; }

        public bool IsSelected { get; set; }

        public List<OptionViewModel> Options { get; set; }

Here is a sample code for another programming challenge, file upload: How to upload files by using ASP.NET Core

Ned Sahin

Blogger for 20 years. Former Microsoft Engineer. Author of six books. I love creating helpful content and sharing with the world. Reach me out for any questions or feedback.

Leave a Comment