简体   繁体   English

asp.net 内核 razor 视图中的可选复选框验证

[英]Optional Checkbox Validation in asp.net core razor view

Following the example found in this stackoverflow post: Radio Buttons with boolean按照此 stackoverflow 帖子中的示例: 带有 boolean 的单选按钮

I'd like to create the same scenario using checkboxes instead of radiobuttons.我想使用复选框而不是单选按钮来创建相同的场景。 Essentially Options: IsDomestic, IsInternational .本质上的选择: IsDomestic, IsInternational So when a user first reaches the view no checkbox should be selected initially.因此,当用户第一次到达视图时,最初不应选择复选框。 So the user has the chance to select an option without one being selected by default due to booleans only being true or false.因此,用户有机会选择 select 一个选项,而不会默认选择一个选项,因为布尔值只有 true 或 false。

so i set these in my model:所以我在我的 model 中设置了这些:

public bool? IsDomestic {get;set;}
public bool? IsInternational {get;set;}

I understand that an initial step would be to make the model fields null-able bools.我知道第一步是使 model 字段可以为空布尔值。 I'd like to implement this using .net cores asp-for="checkbox"我想使用 .net 核心asp-for="checkbox"来实现这个

You don't even need to make the fields nullable.您甚至不需要使这些字段可以为空。 The default value should be false thus showing empty on the view.默认值应为 false,因此在视图上显示为空。 Here is a working example:这是一个工作示例:

Model: Model:

    public class InputModel
    {
        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }

View:看法:

        <div class="form-group">
            <div class="checkbox">
                <label class="float-left" asp-for="Input.RememberMe">
                    <input asp-for="Input.RememberMe" />
                    <label asp-for="Input.RememberMe"></label>
                </label>
                <a class="float-right" asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Sign Up</a>
            </div>
        </div>

Result:结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM