本文介绍了MVC4:单个布尔模型属性的两个单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to find the correct Razor syntax for mutually exclusive radio buttons that both reflect the value of a boolean property on my model. My model has this:

public bool IsFemale{ get; set; }

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

I would like to display this with two radio buttons, one "Male" and the other "Female," but everything I've tried so far has not reflected the actual value of the IsFemale property on the model. Currently, I have this:

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

如果我更改和更新,这似乎可以正确地保留值,但不会将正确的值标记为已选中.我确定这是愚蠢的事情,但我被卡住了.

This seems to persist the value correctly if I change and update, but does not mark the correct value as checked. I'm sure this is something stupid, but I'm stuck.

推荐答案

试试这个:

@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>
}

这篇关于MVC4:单个布尔模型属性的两个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 11:54