Using Html.RadioButtonFor with a boolean isn't writing Checked=“Checked”

落花浮王杯 提交于 2021-02-05 05:43:46

问题


I am having an issue using the RadioButtonFor helper. When the value passed in is true, it isn't displaying a "check" in either radio button. When the value is false, it works just fine.

I copied this code from the project I am working on and created a sample application and I was able to replicate the issue. If I hard coded the value to true or false it seems to work, but when I use the "!string.IsNullOrEmpty(allgroups)" it doesn't.

From the View:

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

From the 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 view source when value of AllGroups is false (note 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>

回答1:


The model binding is getting confused because you named your action parameter the same as your model property. Change the name of your Index action parameter, and it should work.

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



回答2:


if you are returning bool from model then there is no need to check uncheck explicitly mvc will do it itself just write

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

however if you want to do it explicitly then

you should use following syntax to check / uncheck

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

In source code you can see that it is setting true / false for value not checked attribute

in your view you can write

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


来源:https://stackoverflow.com/questions/10629671/using-html-radiobuttonfor-with-a-boolean-isnt-writing-checked-checked

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!