简体   繁体   中英

Radio buttons are rendering as 'checked=checked', not sure of source

I have a page with 8 different radio button groups (groups of 'yes/no' buttons). Originally i had coded the html to render with the 'No' button checked, but now I need to render with no buttons selected.

I removed the 'checked = checked' and refreshed but the NO buttons were still selected. I have refreshed again, cleared the cache, and run on a different browser to no avail. I am looking for assistance locating possible causes.

My MVC code:

@Html.RadioButtonFor(m => m.IsFelon, true, new { @class = "commentBox RadioIf" })
    <label for="PersonModel_Felon">Yes</label>
@Html.RadioButtonFor(m => m.IsFelon, false, new { @class = "commentBox" })
    <label for="PersonModel_Felon">No</label>

How it renders:

<input class="commentBox" data-val="true" data-val-required="The ChildAbusePast field is required." id="ChildAbusePast" name="ChildAbusePast" type="radio" value="True" />
   <label for="HistoryModel_ChildAbusePast">Yes</Label>
<input checked="checked" class="commentBox" id="ChildAbusePast" name="ChildAbusePast" type="radio" value="False" />
   <label for="HistoryModel_ChildAbusePast">No</Label>

Only other thing touching this is some jquery:

$(document).ready(function () {
        $("input.commentBox").click(function () {
            if ($(this).closest('div.editor-field2').children('input:checked').val() == "True") {
               $(this).closest('div.formQuestion').children('div.hidden').slideDown(800);
          } else {
               $(this).closest('div.formQuestion').children('div.hidden').slideUp("fast");
         }
        });
    });

If you didn't initialise IsFelon, then by default, it will be set to "False" which is the nature of the boolean type of object.

On the other hand, if you want the radios to be unselected by default, then you shouldn't be using bool, you would want to use "bool?" which sets the default value to "null" and thus none of the radios will be selected.

Does the IsFelon property of your model have a value? If it's a standard boolean, it will. Thus when you map that property to the radio button whose value is False, MVC recognizes that they match and sets the button to checked .

The easiest solution I can think of is to not map those radio buttons to a model property, but just retrieve those values and set your model property programmatically in the controller on postback. You could also look into making IsFelon a nullable property, but using nullable properties in MVC can involve some fiddling around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM