问题
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