Question How to get list of checkboxes not checked on page model razor page?

ahmedaziz

Well-known member
Joined
Feb 22, 2023
Messages
55
Programming Experience
1-3
I working on razor page with .NET core 7 . my mainly issue How to pass unchecked checkboxes

from html page to page model on post method ?

so If I have group of checkboxes not checked so I need to pass it to page model as List on post method when submit form

so user click submit button then on post method fire then it will collect check boxes not checked values 1 2 3

view model used

UserAccessViewModel:
public class UserAccessViewModel
        {
public int UserId { get; set; }

public UserAccess userAccess { get; set; }
            public int[] checks { get; set; }
        }


on page.cshtml

page model csharp:
@Html.AntiForgeryToken()
<form method="post">
<button id="FillCheckBox" type="submit" class="col-sm-1 btn btn-primary">Submit</button>
<button id="UpdateCheckBox" type="submit" class="col-sm-1 btn btn-primary">Update</button>
<div class="form-group row">
<label for="user-id" class="col-sm-1 col-form-label" style="font-size:15px;font-family: 'Open Sans', sans-serif;font-weight: bold;">User ID</label>
<div class="col-sm-3">
<input id="useraccess-id" name="UserAccessViewModel.UserId" asp-for="UserAccess.UserId" type="text" class="form-control" style=" margin-left:10px;font-size:15px;font-family: 'Open Sans' , sans-serif;font-weight: bold;" />
</div>
</div>
    <input id="StockTake" name="UserAccessViewModel.checks" type="checkbox" asp-for="UserAccess.MODULECODE" value="1">
        <label for="lblStockTake">Stock Take</label>
    <input id="ShelfLabelPrint" name="UserAccessViewModel.checks" type="checkbox" asp-for="UserAccess.MODULECODE" value="2">
        <label for="lblShelfLabel">Shelf Label Print</label>

    <input id="Transfer" name="UserAccessViewModel.checks" type="checkbox" asp-for="UserAccess.MODULECODE" value="3">
        <label for="lblTransfer" style="margin-right:5px;">Transfer</label>

       
        <div class="form-group row">
                   
       
    </form>


on pagemodel .cshtml.cs

on post method pass uncheck checkbox:
public async Task OnPost(UserAccessViewModel UserAccessViewModel)
{
//How to pass checkboxes not checked to razor page
}

for more details what I need
pass unchecked checkboxes to razor page
 
I think that your life would be infinitely easier if you had the checkboxes map to different boolean properties in your UserAccessViewModel. Currently you have all 3 checkboxes all writing to a single property: UserAccessViewModel.MODULECODE. If you had each checkbox setting a different property, then simply counting the properties that are set to false would tell you how many checkboxes are unchecked.
 
See my article ASP.NET Core/Razor pages working with Checkboxes which takes a different approach than what you are doing.

OnPost

Logging in this case is SeriLog

OnPost:
public Task<IActionResult> OnPostResendAsync()
{
    // get checked
    var checkedItems = CheckModels.Where(x => x.Checked).ToList();
    // get unchecked
    var notCheckedItems = CheckModels.Where(x => x.Checked == false).ToList();

    if (checkedItems.Any())
    {
        Log.Information("Checked items on Index1 post");
        foreach (var model in checkedItems)
        {
            Log.Information("Id: {Id} Name: {name}", model.Id, model.Name);
        }
    }
    else
    {
        Log.Information("Nothing check for index1 post");
    }


    return Task.FromResult<IActionResult>(RedirectToPage("Index1"));
}

Property for checkboxes

check boxes property:
[BindProperty]
public List<ServiceModel> CheckModels { get; set; }


Frontend code

frontend code:
<div class="container">

    <form method="post" id="main-content" asp-page-handler="resend" style="width: 23em;">

        <fieldset class="border rounded-3 border-primary p-1">

            <legend class="float-none w-auto fs-6 px-1"
                    id="description">
                <span class="fw-bold">Accessories</span>
            </legend>

            @for (var index = 0; index < Model.CheckModels.Count(); index++)
            {

                <div class="row">

                    <div class="col-6 ms-3">
                        @* note setting initial value of aria-checked using aria_checked*@
                        @Html.HiddenFor(item => @Model.CheckModels[index].Id)
                        @Html.CheckBoxFor(item => @Model.CheckModels[index].Checked,
                    new
                    {
                        @id = @Model.CheckModels[index].Id,
                        @class = "form-check-input",
                        aria_checked = @Model.CheckModels[index].Checked.ToString().ToLower(),
                        aria_label = @Model.CheckModels[index].Name,
                    })

                        <input type="hidden" asp-for="@Model.CheckModels[index].Name" />
                        <label class="form-check-label"
                           for="@Model.CheckModels[index].Id" aria-labelby="@Model.CheckModels[index].Id">
                            @Model.CheckModels[index].Name
                        </label>

                    </div>

                </div>

            }

            <div class="row mt-2 mb-2">

                <div class="ms-3">
                    <input id="resendToken" type="submit" class="btn btn-primary" value="submit" style="width: 130px;" />
                </div>

            </div>
        </fieldset>
    </form>

</div>
 
Notice that at the core of @kareninstructor 's solution, each checkbox is bound to its own distinct property, instead of multiple checkboxes bound to a single property.
 
I have made it in MVC Here the code yu can get inspiration
C#:
public class MyModel
    {
        public int UserId { get; set; }
        public bool StockTakeBool  { get; set; }
        public bool ShelftLabelPrint { get; set; }
        public bool Transfer { get; set; }
    }
HTML:
        <form asp-controller="MyController" asp-action="Create" method="POST">
       
                    <input class="form-check-input" type="checkbox" onchange="document.getElementById('StockTakeBool  ').value = this.checked">                  
                    <input id="StockTakeBool " type="hidden" value="false" asp-for="StockTakeBool  "/>
                    <label class="form-check-label" for="@MyModel.StockTakeBool  ">@Localizer["StockTakeBool  "]</label>

 <input class="form-check-input" type="checkbox" onchange="document.getElementById('ShelftLabelPrint').value = this.checked">                  
                    <input id="ShelftLabelPrint" type="hidden" value="false" asp-for="ShelftLabelPrint"/>
                    <label class="form-check-label" for="@MyModel.ShelftLabelPrint">@Localizer["ShelftLabelPrint"]</label>

 <input class="form-check-input" type="checkbox" onchange="document.getElementById('Transfer').value = this.checked">                  
                    <input id="Transfer" type="hidden" value="false" asp-for="Transfer"/>
                    <label class="form-check-label" for="@MyModel.Transfer">@Localizer["Transfer"]</label>
<button type="submit"/>
       </from>
C#:
[HttpPost]
  [AllowAnonymous]
   public async Task<IActionResult> Create(MyModel model)
{

}
 
Last edited by a moderator:
I have made it in MVC Here the code yu can get inspiration
C#:
public class MyModel
    {
        public int UserId { get; set; }
        public bool StockTakeBool  { get; set; }
        public bool ShelftLabelPrint { get; set; }
        public bool Transfer { get; set; }
    }
Only thing id say with that is the names could do with some improvement, perhaps like IsStockTakeRequired, IsLabelReprintRequested, ShouldTransferDuringUpdate - make the names more descriptive of the business logic applied to them, and make them obviously bool flavoured with words like Is or Should. Don't suffix bool onto the name, and avoid bland names that could be nouns or verbs, like Transfer
 
Back
Top Bottom