单选按钮多的bool [英] Radio Button For multiple bools
问题描述
说我有在我的模型如下性质,我想成为相互排斥:
Say I have the following properties in my model that I want to be mutually exclusive:
public bool PrintWeek1 {get; set;}
public bool PrintWeek2 {get; set;}
public bool PrintWeek3 {get; set;}
是否有可能使这些为一组单选按钮或者我需要将其更改为一个枚举?
Is it possible to render these as a set of radio buttons or do I need to change them to an enum?
如果我用 @ Html.RadioButtonFor
它呈现的名称作为属性的名称,使他们没有被正确分类。
If I use @Html.RadioButtonFor
it renders name as the name of the property so they aren't grouped correctly.
推荐答案
又来了一个快速的解决方案,让你在型号具有以下属性 -
Here comes a quick solution, let you have following properties in Model -
public bool PrintWeek1 { get; set; }
public bool PrintWeek2 { get; set; }
public bool PrintWeek3 { get; set; }
public string SelectedValue { get; set; }
那么你的HTML应该是这样的 -
Then your HTML should be like this -
@Html.RadioButtonFor(Model => Model.PrintWeek1, "PrintWeek1", new { @Name = "SelectedValue" })
@Html.RadioButtonFor(Model => Model.PrintWeek2, "PrintWeek2", new { @Name = "SelectedValue" })
@Html.RadioButtonFor(Model => Model.PrintWeek3, "PrintWeek3", new { @Name = "SelectedValue" })
然后,当您提交表单,您将获得在选定值的SelectedValue
属性。
修改
要地址@StephenMuecke点,创造了以下的解决方案 -
EDIT To Address @StephenMuecke point, created the below solution -
创建一个枚举
-
public enum PrintWeekType
{
PrintWeek1, PrintWeek2, PrintWeek3
}
然后有一个模型属性(而不是单个属性,有单emum属性) -
Then have a model property (instead of individual properties, have single emum property) -
public PrintWeekType SelectedValue { get; set; }
HTML应该像下面 -
HTML should be like below -
@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek1)
@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek2)
@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek3)
使用上面的例子中,我们可以pre-选择一个单选按钮,在同一时间,我们可以发布所选值的SelectedValue
属性。
这篇关于单选按钮多的bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!