Pages

Nov 9, 2016

Handling dynamically created RadioButtons in ASP.NET MVC

Model



Controller



View

 
<![CDATA[
    @model ExampleViewModel
    @using (Html.BeginForm())
    {
        <table class="table table-bordered table-striped">
            @for(int i=0;i<Model.Questions.Count;i++)
            {
                var question = Model.Questions[i];
                <tr>
                    <td>
                        @foreach (var answer in question.Value)
                        {
                            <input type="text" name="Model.Answers[@question.Key].Key" value="@question.Key" />
                            <input type="hidden" name="Model.Answers.Index" value="@question.Key" />
                            @Html.RadioButton("Model.Answers[" + question.Key+"].Value", answer, false) @answer
                        }
                    </td>
                </tr>
            }
            <tr>
                <td>
                    <input type="submit" class="btn btn-primary" value="Submit" />
                </td>
            </tr>
        </table>
    }
]]>

In model.Questions text and values for the radio button can be added through controller. When the form is submitted ASP.NET MVC Model model.Answers will hold the dictionary containing the submitted values,