Multiple radio buttons for the Model field in ASP.NET MVC

Posted by Sheonarayan under ASP.NET MVC category on | Points: 40 | Views : 5534
To render multiple radio buttons for the Model field in ASP.NET MVC, write following code.

<div class="editor-label">
@Html.LabelFor(model => model.IsAnswerTypeSubjective)
<div class="editor-field">
@Html.RadioButtonFor(m => m.IsAnswerTypeSubjective, "false", new { id = "iatsFalse", @checked = "checked"} )
@Html.Label("iatsFalse", "Objective (Multiple choices)")
@Html.RadioButtonFor(m => m.IsAnswerTypeSubjective, "true", new { id = "iatsTrue"} )
@Html.Label("iatsTrue", "Subjective")
@Html.ValidationMessageFor(model => model.IsAnswerTypeSubjective)


In above code, my field name is IsAnswerTypeSubjective and the value for two radio buttons are "false" and "true" respectively.

The third parameter for RadioButtonFor helper method is the id attribute of the radio button that is used to write label for it.

The above code renders following HTML code

<div class="editor-label">
<label for="IsAnswerTypeSubjective">Question type (Multiple choices or Subjective)</label>
<div class="editor-field">
<input data-val="true" data-val-required="The Question type (Multiple choices or Subjective) field is required." id="iatsFalse" name="IsAnswerTypeSubjective" type="radio" value="false" />
<label for="iatsFalse">Objective (Multiple choices)</label>
<input id="iatsTrue" name="IsAnswerTypeSubjective" type="radio" value="true" />
<label for="iatsTrue">Subjective</label>

<span class="field-validation-valid" data-valmsg-for="IsAnswerTypeSubjective" data-valmsg-replace="true"></span>

Hope this this will be useful.

Comments or Responses

Login to post response