【问题标题】:MVC4: Two radio buttons for a single boolean model propertyMVC4:单个布尔模型属性的两个单选按钮
【发布时间】:2012-05-18 02:26:43
【问题描述】:

我正在尝试为互斥单选按钮找到正确的 Razor 语法,这些单选按钮都反映了我模型上布尔属性的值。我的模型有这个:

public bool IsFemale{ get; set; }

我想用两个单选按钮来显示这个,一个是“男性”,另一个是“女性”,但到目前为止我所做的一切都没有反映模型上 IsFemale 属性的实际值。目前,我有这个:

@Html.RadioButtonFor(model => model.IsFemale, !Model.IsFemale) Male
@Html.RadioButtonFor(model => model.IsFemale, Model.IsFemale) Female

如果我更改和更新,这似乎可以正确保留值,但不会将正确的值标记为已选中。我确定这很愚蠢,但我被困住了。

【问题讨论】:

  • 您的应用文化是什么?您使用的是本地化的 .net 吗?因为我无法重现您的问题,并且因为达林的解决方案有效,所以这可能是一些文化设置问题......
  • 我目前没有设置文化,所以我假设它使用的是机器默认值。
  • 有趣...这很奇怪,因为我也希望它可以像您尝试的那样工作,实际上它在我的复制中也可以...

标签: asp.net-mvc razor asp.net-mvc-4 radiobuttonfor


【解决方案1】:

在 MVC 6 (ASP.NET Core) 中,这也可以通过标签助手来实现:

<label>
    <input type="radio" asp-for="IsFemale" value="false" /> Male
</label>
<label>
    <input type="radio" asp-for="IsFemale" value="true" /> Female
</label>

【讨论】:

    【解决方案2】:

    试试这样:

    @Html.RadioButtonFor(model => model.IsFemale, "false") Male
    @Html.RadioButtonFor(model => model.IsFemale, "true") Female
    

    这是完整的代码:

    型号:

    public class MyViewModel
    {
        public bool IsFemale { get; set; }
    }
    

    控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel
            {
                IsFemale = true
            });
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return Content("IsFemale: " + model.IsFemale);
        }
    }
    

    查看:

    @model MyViewModel
    
    @using (Html.BeginForm())
    {
        @Html.RadioButtonFor(model => model.IsFemale, "false", new { id = "male" }) 
        @Html.Label("male", "Male")
    
        @Html.RadioButtonFor(model => model.IsFemale, "true", new { id = "female" })
        @Html.Label("female", "Female")
        <button type="submit">OK</button>
    }
    

    【讨论】:

    • 是的,这行得通。这对我来说似乎完全违反直觉,因为RadioButtonFor 的重载将该参数指定为object value。非常感谢!
    • 很好的答案。也适用于标签点击。
    • 在我的情况下,默认值为 false,如果我不单击无线电进行更改,那么在提交时我会收到 true。 @Html.RadioButtonFor(m => m.IsWorkDefaultAddress, "true", new { id = "default-work" }) @Html.RadioButtonFor(m => m.IsWorkDefaultAddress, "false", new { id = "default-家”})
    • 如果您不希望选择任何单选按钮,则将 IsFemale 设为可为空的“布尔?”并设置 IsFemale = null。
    • 为什么像@Html.RadioButtonFor(model =&gt; model.IsFemale, false, new { id = "male" }) 这样的真正布尔值不起作用?
    猜你喜欢
    • 2021-10-23
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多