Create.cshtml // Rest form code removed for brevity
<div class="form-group">
<label for="GradingKey.HalfScoresCount">
<input asp-for="GradingKey.HalfScoresCount" value="true" type="radio" />Yes
</label>
<span asp-validation-for="GradingKey.HalfScoresCount" class="text-danger" />
</div>
<div class="form-group">
<label for="GradingKey.HalfScoresCount">
<input asp-for="GradingKey.HalfScoresCount" value="false" type="radio" />No
</label>
<span asp-validation-for="GradingKey.HalfScoresCount" class="text-danger" />
</div>
Created Html
<div class="form-group">
<label for="GradingKey.HalfScoresCount">
<input value="true" type="radio" data-val="true" data-val-required="Das Feld "HalfScoresCount" ist erforderlich." id="GradingKey_HalfScoresCount" name="GradingKey.HalfScoresCount" />Yes
</label>
<span class="text-danger field-validation-valid" data-valmsg-for="GradingKey.HalfScoresCount" data-valmsg-replace="true" />
</div>
<div class="form-group">
<label for="GradingKey.HalfScoresCount">
<input value="false" type="radio" id="GradingKey_HalfScoresCount" name="GradingKey.HalfScoresCount" />No
</label>
<span class="text-danger field-validation-valid" data-valmsg-for="GradingKey.HalfScoresCount" data-valmsg-replace="true" />
</div>
Why has the generated html the same id for both radio buttons?
How can I avoid that?
The only thing you have to change in your code is the name of the radio button because all radio buttons with the same name are assumed to be a group, and the web-browser only allows selection of only one of them by default, and you cannot control that.
Radio buttons allow a user to select a single option among multiple options. You can set the Choice Value of each option, for each button, as well as group these buttons by giving them the same Group Name.
In this case, the first radio button is now selected by default. Note: If you put the checked attribute on more than one radio button, later instances will override earlier ones; that is, the last checked radio button will be the one that is selected.
Why has the generated html the same id for both radio buttons?
By default, the id
field for an input
will be the name of the property set in the asp-for
tag helper value. You've got the same value listed twice:
<input asp-for="GradingKey.HalfScoresCount" value="true" type="radio" />Yes
<input asp-for="GradingKey.HalfScoresCount" value="false" type="radio" />No
How can I avoid that?
Simply specify your own id
attribute values:
<input asp-for="GradingKey.HalfScoresCount" value="true" type="radio" id="myFirstId" />Yes
<input asp-for="GradingKey.HalfScoresCount" value="false" type="radio" id="mySecondId" />No
As long as you do not modify the name
attribute, the model binding will still function properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With