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

View:

<form method="post">
	<div class="container">
		<h4>Question</h4>
		<div>
			<h5>@Model.QuestionViewModel.QuestionText</h5>
		</div>
	</div>

	<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>

</form>

ViewModel:

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

Leave a Comment