Jonathan
Jonathan

Reputation: 651

Checkbox input always return false value

I'm using asp.net core 2.1 and I have a simple view with form like:

@model Security.WebUi.Pages.AssignClaimToUserModel

<form method="post">
    <div>
        <label>User:  </label>
        <select asp-for="UserId" asp-items="@Model.UserList">
            <option>Please select one</option>
        </select>
    </div>
    <div>
        <label>Role?</label>
        <input type="checkbox" name="IsRole" id="isRole" />
    </div>
    <div>
        <label>Claim Type</label>
        <input type="text" name="ClaimType" id="claimType" />
    </div>
    <div>
        <label>Claim Value</label>
        <input type="text" name="ClaimValue" />
    </div>
    <button type="submit">Submit</button>
</form>

As you can see I have a checkbox with IsRole property

So in my model I have a boolean:

 public class ClaimToUserdModel
    {
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }
        public Guid UserId { get; set; }
        public bool IsRole { get; set; }
    }

then in method I call as:

public async Task<IActionResult> OnPost(ClaimToUserdModel model)
            {
              ....
            }

But it always throw false, it does not care about checked or not. What am I doing wrong?

Upvotes: 1

Views: 3002

Answers (2)

A.M. Patel
A.M. Patel

Reputation: 334

I got the same issue, I fixed it by writing html checkbox tag, giving it the name same as property name, and value = true, if the checkbox is not checked no need to worry as it won't be submitted anyway, in your case this will be it

<input type="checkbox" name="Remember" value="true" checked="@Model.YourmodelPropertyname"/>

also you set checkbox checked property value using jquery.

Upvotes: 5

Nan Yu
Nan Yu

Reputation: 27578

You can use try :

<input type="checkbox" name="IsRole" id="isRole" value="true" />

It seems you are using ASP.NET Core Razor Page ,you can also refer to below sample :

@page
@model razorpages.Pages.AssignClaimToUserModel
@{
    ViewData["Title"] = "AssignClaimToUser";
}

<form method="post">

<div>
    <label>Role?</label>      
    <input asp-for="ClaimToUserdModel.IsRole" name="IsRole">
</div>

<button type="submit">Submit</button>

Code behind :

public class AssignClaimToUserModel : PageModel
{
    public ClaimToUserdModel ClaimToUserdModel;
    public void OnGet()
    {

    }

    public async Task<IActionResult> OnPost(ClaimToUserdModel model)
    {
        return null;
    }
}

public class ClaimToUserdModel
{
    public string ClaimType { get; set; }
    public string ClaimValue { get; set; }
    public Guid UserId { get; set; }
    public bool IsRole { get; set; }
}

Upvotes: 0

Related Questions