【问题标题】:Radio Button For multiple bools多个布尔值的单选按钮
【发布时间】:2015-06-24 07:44:39
【问题描述】:

假设我的模型中有以下我想要互斥的属性:

public bool PrintWeek1 {get; set;}
public bool PrintWeek2 {get; set;}
public bool PrintWeek3 {get; set;} 

是否可以将它们呈现为一组单选按钮,或者我是否需要将它们更改为枚举?

如果我使用 @Html.RadioButtonFor,它会将 name 呈现为属性的名称,因此它们不会被正确分组。

【问题讨论】:

  • 你可以给你自己的名字 - new { @Name= "grp" },这样它们就会被组合在一起。
  • 单个枚举属性(具有 3 个值和 3 个对应的单选按钮)会更有意义
  • @ramiramilu 啊,我正在尝试使用 new {@name = "grp"},它没有覆盖 MVC 正在呈现的名称。我现在会检查他们是否正确回复..
  • 实际上它适用于互斥,但是更改名称实际上会在posting模型中产生问题。您实际上是如何将数据发回服务器的?相反,我建议您使用RadioButtonListFor,如下所示 - stackoverflow.com/questions/21679249/…

标签: asp.net asp.net-mvc


【解决方案1】:

这里有一个快速的解决方案,让你在模型中拥有以下属性 -

public bool PrintWeek1 { get; set; }
public bool PrintWeek2 { get; set; }
public bool PrintWeek3 { get; set; }
public string SelectedValue { get; set; }

那么你的 HTML 应该是这样的 -

@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 点,创建了以下解决方案 -

创建一个enum -

public enum PrintWeekType
{
    PrintWeek1, PrintWeek2, PrintWeek3
}

然后有一个模型属性(而不是单个属性,有单个 emum 属性) -

public PrintWeekType SelectedValue { get; set; }

HTML 应该如下所示 -

@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek1) 
@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek2) 
@Html.RadioButtonFor(m => m.SelectedValue, PrintWeekType.PrintWeek3)

使用上面的示例,可以预先选择一个单选按钮,同时我们可以在SelectedValue属性中发布选择的值。

【讨论】:

  • 这不起作用并提供 2 路模型绑定。首次呈现视图时,无论boolean 属性的值如何,都不会选择单选按钮
  • @StephenMuecke 你是对的,用更精确的解决方案更新了我的答案:-)
【解决方案2】:

好的,我放弃了布尔值并最终使用了一个列表 - 这似乎是最快和最简单的方法。

我在哪里初始化我的模型:

   public PrintViewModel()
        {
            this.PrintTypes = new List<string>() { "Print Week 1", "Print Week 2", "Print Week 3" };
        }

    public List<string> PrintTypes { get; set; }
    public string SelectedPrintType { get; set; }

在我看来(我希望默认选择第一个选项):

   @for(int i = 0; i < Model.PrintTypes.Count; i++)
        {
            <div class="row">
                <div class="col-md-2">
                    @(i == 0 ? Html.RadioButtonFor(x => x.SelectedPrintType, Model.PrintTypes[i], new {@checked = "checked"}) : @Html.RadioButtonFor(x => x.SelectedPrintType, Model.PrintTypes[i]))
                    &nbsp;
                    <label for="@Model.PrintTypes[i]">@Model.PrintTypes[i]</label>
                </div>
            </div>
        }

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2015-04-27
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2016-11-01
    • 2021-10-23
    • 2021-12-24
    • 2019-04-19
    相关资源
    最近更新 更多