【问题标题】:Radio button always checked item show False单选按钮始终选中项目显示 False
【发布时间】:2019-01-23 02:19:08
【问题描述】:

我有一个 Razor 单选按钮,但总是选中的项目显示为 false。

代码

    @using (Html.BeginForm("NewsSubmit", "Home", FormMethod.Post))
            {
                <div class="card-body pt-5 flex-center flex-column">
                    <form class="form-checkout form-style-1">
                        <div class="form-group text-center mt-3 shipping-group">

                                @Html.RadioButtonFor(x=>x.IsUseRegisteredAddress,true,new { @class = "custom-control-input", @checked = " " })

                                @Html.RadioButtonFor(x => x.IsUseRegisteredAddress, false, new { @class = "custom-control-input",@checked = " " })

                        </div>
                   </form>
                 </div>
           }

控制器

Public ActionResult NewsSubmit(NewsTotal news)
{
return View();
}

DTO

public class NewsTotal()
{
public bool IsUseRegisteredAddress{get;set;}
}

【问题讨论】:

  • 你的问题到底是什么?
  • @JosueMartinez 当我选择第一个单选按钮时,它的值为 true..但它也显示为 False

标签: c# asp.net asp.net-mvc razor


【解决方案1】:

问题似乎来自定义为 bool 的 viewmodel 属性的声明,当您使用 return View(news) 收到 NewsTotal 时,您也没有从控制器设置它:

public bool IsUseRegisteredAddress { get; set; }

由于bool的默认值在未设置时为false,因此默认选中具有false值的单选按钮。如果你想使用true 作为默认值,你需要从返回viewmodel的控制器动作中设置它:

[HttpPost]
public ActionResult NewsSubmit(NewsTotal news)
{    
    // set radio button state (optional, ignore this if it's already set in 'news' parameter)
    news.IsUseRegisteredAddress = true;

    // returning viewmodel is mandatory
    return View(news);
}

或者,如果您想将所有单选按钮设置为默认未选中,请指定Nullable&lt;bool&gt; viewmodel 属性:

public bool? IsUseRegisteredAddress { get; set; }

注意事项:

1) 您可以考虑从RadioButtonFor 中删除@checked 属性,因为checked 是布尔属性,它表示属性存在时的选中状态(并且在属性不存在时未选中),如下所示:

@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, true, new { @class = "custom-control-input" }) Yes

@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, false, new { @class = "custom-control-input" }) No

如果checked 属性出现在两个具有相同名称或组的单选按钮中,则默认情况下将最后一个具有checked 属性的单选按钮设置为选中。

2) 第二个表单&lt;form class="form-checkout form-style-1"&gt; 无效,因为它会创建嵌套表单。删除 Html.BeginForm 助手中的额外表单标签,并改为设置主表单的样式:

@using (Html.BeginForm("NewsSubmit", "Home", FormMethod.Post, new { @class = "form-checkout form-style-1" }))
{
    // form contents
}

【讨论】:

  • 有两个单选按钮,当我检查第一个时,我需要将我的属性设置为 True,当我单击第二个时,我需要将我的属性设置为 False
  • 考虑寻找this fiddle - 您的问题不仅仅是属性,它还有嵌套表单。请删除第二个form 标签。
【解决方案2】:

检查单选按钮的正确方法如下:

@Html.RadioButtonFor(x=&gt; x.IsUseRegisteredAddress, "Registered", new { @checked = true })

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 2013-12-26
    • 2016-09-28
    • 2014-01-13
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多