MVC4:对于一个布尔模型属性两个单选按钮 [英] MVC4: Two radio buttons for a single boolean model property

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

问题描述

我试图找到相互排斥的单选按钮,这两个反映布尔属性对我的模型数值正确的剃刀语法。我的模型有这样的:

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

这是完整的code:

型号:

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:对于一个布尔模型属性两个单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆