I have a seemingly easy task of setting a radio button \"checked\" based on model\'s boolean value. I have a boolean in my model \"IsSDPDonor\" which I want to use it for Ye
Create the HTML options in a code block, leaving them null if the button shouldn't be checked, then use the proper variable in your helper.
@{
var yesOptions = Model.Donor.IsSDPDonor ? new { @checked = "checked" } : null;
var noOptions = Model.Donor.IsSDPDonor ? null : new { @checked = "checked" };
}
@Html.Label("Would You Like to Donate Platelets (SDP)") :
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, true, yesOptions ) Yes
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, false, noOptions ) No
EDIT: After looking at the source code, it appears to me that it should be setting this property based on the value of the model. Have you tried omitting the HTML attributes completely?
case InputType.Radio:
if (!usedModelState) {
string modelStateValue = htmlHelper.GetModelStateValue(name, typeof(string)) as string;
if (modelStateValue != null) {
isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
usedModelState = true;
}
}
if (!usedModelState && useViewData) {
isChecked = htmlHelper.EvalBoolean(name);
}
if (isChecked) {
tagBuilder.MergeAttribute("checked", "checked");
}
tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
break;