【问题标题】:ASP.net MVC - radio button validation is not workingASP.net MVC - 单选按钮验证不起作用
【发布时间】:2019-08-26 17:56:19
【问题描述】:

我有一个显示布尔字段的单选按钮。当我在未选中单选按钮的情况下提交表单数据时,它不会保存为必填字段,但不会显示验证消息。所有文本框都显示验证消息,只有单选按钮不显示验证消息。

我已添加:

  • [Required] 到视图模型中的字段
  • @Html.ValidationMessageFor(m => m.isCurrent)在视图中

但是,它仍然没有显示错误消息。

有没有人遇到过类似的问题?

视图模型

    [Required]
    public bool? isCurrent { get; set; }

查看

<label type='checkbox'>
    Is this bus still a part of your fleet?
    <div>
        @Html.RadioButtonFor(m => m.isCurrent, true, new {id = "Yes"}) @Html.Label("Yes", "Yes")
        @Html.RadioButtonFor(m => m.isCurrent, false, new {id = "No"}) @Html.Label("No", "No")
        @Html.ValidationMessageFor(m => m.isCurrent)
    </div>
</label>

【问题讨论】:

  • 您是否启用了客户端验证和不显眼的 Javascript?
  • 还可以检查一下剃须刀页面是否引用了验证 js 文件。

标签: html asp.net-mvc


【解决方案1】:

您需要添加@Html.ValidationMessageFor。还要确保在视图底部包含 jquery 验证包或脚本。例如:

@using (Html.BeginForm())
{
<label type='checkbox'>
    Is this bus still a part of your fleet?
    <div>
        @Html.RadioButtonFor(m => m.isCurrent, true, new { id = "Yes" }) @Html.Label("Yes", "Yes")
        @Html.RadioButtonFor(m => m.isCurrent, false, new { id = "No" }) @Html.Label("No", "No")
        @Html.ValidationMessageFor(m => m.isCurrent)
    </div>
    @Html.ValidationMessageFor(model => model.isCurrent, "", new { @class = "text-danger" })
</label>
    <input type="submit" value="send" />
}


@section scripts{
    @Scripts.Render("~/bundles/jqueryval")
}

希望这有帮助:)

【讨论】:

    【解决方案2】:

    我想通了伙计们。我需要将单选按钮包装到 RadioButtonList 中。

    @Html.RadioButtonFor(m => m.isCurrent, true, new {id = "Yes"}) @Html.Label("Yes", "Yes") @Html.RadioButtonFor(m => m.isCurrent , false, new {id = "No"}) @Html.Label("No", "No") @Html.ValidationMessageFor(m => m.isCurrent)

    【讨论】:

    • 我刚刚为您提供了与上面相同的答案,已成功构建和测试。
    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 2020-04-12
    • 2017-07-21
    • 2020-02-02
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    相关资源
    最近更新 更多