Reputation: 27350
How do I ensure that a radio button list has the first option selected? If it is based on the model property, how is this set if this is the first page that is shown on application start-up?
This is easy peasy in webforms but I don't know how to do this in MVC and there doesn't seem to be anywhere on the NET which shows how this is done.
This doesn't seem to work:
@Html.RadioButtonFor(m => m.SearchType, true) Location
@Html.RadioButtonFor(m => m.SearchType, false) Name
I Just get both radio buttons unselected??
Upvotes: 4
Views: 21054
Reputation: 4549
Very interesting status, i agree both of above, for users who looking also checkbox can use below examples, and for radio button default i reversed the array, in my case below is right!
<div class="row">
<div class="col-xs-6">
@for (int idx = 0; idx < Model.TldList.Count; idx++)
{
<div>
@Html.HiddenFor(x => Model.TldList[idx].Id)
@Html.CheckBoxFor(x => Model.TldList[idx].IsSelected)
@Html.DisplayFor(x => Model.TldList[idx].Name)
</div>
}
</div>
<div class="col-xs-6">
@for (int idx = Model.Period.Count-1; idx >= 0; idx--)
{
<div>
@Html.RadioButtonFor(x => Model.Period, Model.Period[idx].Id, new { @checked = Model.Period[idx].IsSelected })
<span>@Model.Period[idx].Name</span>
</div>
}
</div>
</div>
Upvotes: 0
Reputation: 4870
@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = true })
Upvotes: 13
Reputation: 187
This was my solution:
@Html.RadioButtonFor(model => model.Coin , "Dollar", Model.Coin == "$" ? (new { @checked = "checked" }) : null)
@Html.RadioButtonFor(model => model.Coin , "Euro", Model.Coin == "E" ? (new { @checked = "checked" }) : null)
Upvotes: 4
Reputation: 14297
@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = "checked"})
or if you are binding from model then
@Html.RadioButtonFor(x => x.Something, "radioValue", new { @checked = Model.checked})
if we try something like this where x.checked is binding from the database. irrespective of true or false. last radio-button in the list is checked, rest of them are unchecked.
how can we bind the Radio button list from Database and have it worked correctly?
Upvotes: 6