0

Following the example found in this stackoverflow post: Radio Buttons with boolean

I'd like to create the same scenario using checkboxes instead of radiobuttons. Essentially Options: 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.

so i set these in my 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. I'd like to implement this using .net cores asp-for="checkbox"

1
  • With checkboxes though, they could potentially choose both of them unless you've got some additional (imo unnecessary) steps to prevent the two being checked. Are you sure you don't need two radio buttons? Commented May 31, 2020 at 16:10

1 Answer 1

0

You don't even need to make the fields nullable. The default value should be false thus showing empty on the view. Here is a working example:

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:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.