asp.net mvc3 checking radio button based on model

后端 未结 1 797
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 09:08

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

相关标签:
1条回答
  • 2021-01-02 09:13

    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;
    
    0 讨论(0)
提交回复
热议问题