C# 单选按钮始终选中项目显示错误
我有一个剃须刀单选按钮,但总是检查项目显示错误 代码 DTOC# 单选按钮始终选中项目显示错误,c#,asp.net,asp.net-mvc,razor,C#,Asp.net,Asp.net Mvc,Razor,我有一个剃须刀单选按钮,但总是检查项目显示错误 代码 DTO 检查单选按钮的正确方法如下: @Html.radiobutton(x=>x.isUserRegisteredAddress,“Registered”,new{@checked=true})问题似乎来自于viewmodel属性的声明,该属性定义为bool,而且当您通过使用返回视图(新闻)收到NewsTotal时,您也没有从控制器设置它: 由于未设置时bool的默认值为false,因此默认选中具有false值的单选按钮。如果要使用true
检查单选按钮的正确方法如下:
@Html.radiobutton(x=>x.isUserRegisteredAddress,“Registered”,new{@checked=true})
问题似乎来自于viewmodel属性的声明,该属性定义为bool
,而且当您通过使用返回视图(新闻)
收到NewsTotal
时,您也没有从控制器设置它:
由于未设置时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
viewmodel属性:
public bool? IsUseRegisteredAddress { get; set; }
注意事项:
< P > 1)您可以考虑从<代码> RealButoOng/<代码>中删除<代码> @检查/ <代码>属性,因为<代码>检查< /COD>是布尔属性,它表示属性存在时的选中状态(在属性不存在时未选中),如下所示:
@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, true, new { @class = "custom-control-input" }) Yes
@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, false, new { @class = "custom-control-input" }) No
如果选中的
属性出现在两个同名或组的单选按钮中,则默认情况下,最后一个具有选中的
属性的单选按钮将设置为选中
2) 第二个表单
无效,因为它将创建嵌套表单。删除Html.BeginForm
helper中的其他表单标记,并改为设置主表单的样式:
@using (Html.BeginForm("NewsSubmit", "Home", FormMethod.Post, new { @class = "form-checkout form-style-1" }))
{
// form contents
}
你的问题到底是什么?@JosueMartinez当我选择第一个单选按钮时,它的值为真。但它也显示为假有两个单选按钮,当我选中第一个时,我需要设置我的属性为真,当我单击第二个时,我需要设置我的属性为假考虑寻找-你的问题不仅仅是属性,它也有嵌套的表单。请删除第二个
表单
标签。
[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);
}
public bool? IsUseRegisteredAddress { get; set; }
@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, true, new { @class = "custom-control-input" }) Yes
@Html.RadioButtonFor(x => x.IsUseRegisteredAddress, false, new { @class = "custom-control-input" }) No
@using (Html.BeginForm("NewsSubmit", "Home", FormMethod.Post, new { @class = "form-checkout form-style-1" }))
{
// form contents
}