单选按钮始终选中的项目显示为False

时间:2019-01-23 02:19:08

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

我有一个Razor单选按钮,但始终选中的项目显示为假。

代码

[CmdletBinding()]
param (
    [string[]] 
    $Files
)

$badCharacters = @"
‘
’
–
"@

$badCharactersList = $badCharacters -split "`r`n"

if (-not $Files)
{
    $Files = @('D:\test\badchars.txt')
}

foreach ($file in $Files)
{
    Write-Progress -Activity "Checking file: $file..."
    $contents = Get-Content $file -Encoding UTF8
    $lineNumber = 1
    foreach ($line in $contents)
    {
        foreach ($invalidChar in $badCharactersList)
        {
            if ($line -match $invalidChar)
            {
                Write-Output "Invalid Character found: f=$file, l=$lineNumber, c=$invalidChar"
                break
            }
        }

        $lineNumber++
    }
}

控制器

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

DTO

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

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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<bool> viewmodel属性:

public bool? IsUseRegisteredAddress { get; set; }

注释:

1)您可能考虑从@checked中删除RadioButtonFor属性,因为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)第二种形式<form class="form-checkout form-style-1">无效,因为它将创建嵌套形式。移除Html.BeginForm帮助器中的其他表单标签,并设置主表单的样式:

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