来自数据库的单选按钮名称和ID。这就是我所做的。
foreach (var radiobtn in Model.PrintLocations)
{
if (int.Parse(radiobtn.Value) < 3)
{
<td>
@Html.RadioButtonFor(m => m.PrintLocation, radiobtn.Value.ToString())
@radiobtn.Text
</td>
}
}
我的要求是默认选择标识为1
的选择单选按钮。
请帮助。
答案 0 :(得分:0)
你可以做这样的事情
foreach (var radiobtn in Model.PrintLocations)
{
if (int.Parse(radiobtn.Value) < 3)
{
<td>
if(yourCondition)
{
@Html.RadioButtonFor(m => m.PrintLocation, radiobtn.Value.ToString())
}
else
{
@Html.RadioButtonFor(m => m.PrintLocation, radiobtn.Value.ToString(), new { @checked = "checked" })
}
@radiobtn.Text
</td>
}
}
其他方式(如果你不想要“脏”的html代码)是通过javascript(或jquery)选择收音机
希望我帮助
答案 1 :(得分:0)
您可以使用RadioButtonListFor帮助程序。
如果您使用的是Twitter Bootstrap,则可以使用TwitterBootstrapMVC。它内置了这个帮助器。否则你可以从here获取并调整它的代码。您可以从here(scrool down到 CheckBoxList / RadioButtonList )获得使用此类帮助程序的示例。
这个助手的美妙之处在于PrintLocations
可以是任何IEnumerable
- 不仅仅是IEnumerable<SelectListItem>
。
快速代码示例:
@(Html.Bootstrap().RadioButtonListFor(
m => m.PrintLocation,
m => m.PrintLocations,
loc => loc.Value,
loc => loc.Text)
.SelectedValues(loc => loc.Value == 1))
我建议这个助手有两个原因。首先,因为我构建了它:)其次,它使用流畅的语法。
还有另一个类似的东西很酷的助手,它不会产生与Bootstrap相关的标记:CheckBoxList(For)。看看吧!