Using Html.RadioButtonFor with Boolean Doesn't Write Checked = "Checked"

I have a problem with the RadioButtonFor helper. When a value is set to true, it does not display a "check" in any switch. When the value is false, it works fine.

I copied this code from a project I'm working on, and created a sample application, and I was able to replicate the problem. If I hardcoded true or false, it worked, but when I use "! String.IsNullOrEmpty (allgroups)", it is not.

From view:

<div>
    @Html.RadioButtonFor(m => m.AllGroups, true) All Groups
    @Html.RadioButtonFor(m => m.AllGroups, false) Current Groups
</div>

From ViewModel:

    public bool AllGroups { get; set; }

From the controller:

public ActionResult Index(string allgroups)
{
    var model = new ProgramGroupIndexViewModel
      {
          AllGroups = !string.IsNullOrEmpty(allgroups)
      };
    return View(model);
}

From view source in IE:

<div>
    <input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
    <input id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>

From the view source, when the value of AllGroups is false (note that it works):

<div>
    <input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
    <input checked="checked" id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>
+3
source share
2 answers

, , . Index, .

public ActionResult Index(string showAllGroups)
{
    var model = new ProgramGroup
                    {
                        AllGroups = !string.IsNullOrEmpty(showAllGroups);
                    };
    return View(model);
}
+2

bool , uncheck mvc ,

<div>
    @Html.RadioButtonFor(m => m.AllGroups) 
    @Html.RadioButtonFor(m => m.AllGroups)
</div>

, ,

/

Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { @checked = "checked" })

, true/false ,

@if(m.AllGroups)
{
  Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { @checked = "checked" })
}
else
{
   Html.RadioButtonFor(m => m.AllGroups, "DisplayText" })
}
-1

All Articles