How to get checkbox have checked false or not checked on post method on mvc razor page?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-05-13T12:56:16.9866667+00:00

I work on mvc razor page I face issue I can't get checkbox not checked or have checked false on post method on page model csharp .

Only I can get selected checkbox true .

@Html.AntiForgeryToken()
    <form method="post">
    <button id="FillCheckBox" type="submit" class="col-sm-1 btn btn-primary">Submit</button>
    <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>
 
    </form>

I use view model as below

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

on page model asp.net razor

public async Task OnPost(UserAccessViewModel UserAccessViewModel)
        {
           //How to get transfer checkbox not checked that have checked false
        }

more details about what i need

checkbox not checked not display on page model

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,404 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,419 questions
{count} votes

3 answers

Sort by: Most helpful
  1. AgaveJoe 27,696 Reputation points
    2023-05-14T01:13:04.79+00:00

    Below is a basic data driven checkbox example.

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <form method="post">
            <table>
                @foreach (var option in Model?.Options)
                {
                    <tr>
                        <td>
                            <input type="checkbox" name="Selections" value="@option.Value" checked="@option.Selected" />
                        </td>
                        <td>
                            <label for="@option.Value">@option.Text</label>
                        </td>
                    </tr>
                }
            </table>
            <br />
            <input type="submit" value="Submit" />
        </form>
    </div>
    
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.EntityFrameworkCore;
    using RazorPagesSqlite.Data;
    using RazorPagesSqlite.Models;
    using System.Collections.Generic;
    
    namespace RazorPagesSqlite.Pages
    {
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
            private readonly ApplicationDbContext _context;
    
            public IndexModel(ILogger<IndexModel> logger, ApplicationDbContext context)
            {
                _logger = logger;
                _context = context;
            }
    
            public async Task OnGetAsync()
            {
                Options = await PopulateOptions();
            }
    
            public async Task OnPostAsync(List<string> Selections)
            {
                Options = await PopulateOptions();
                foreach(var selection in Selections)
                {
                   Options.FirstOrDefault(o => o.Value == selection).Selected = true;
                }
            }
    
            public List<SelectListItem>? Options { get; set; } = default!;
    
    
            private async Task<List<SelectListItem>> PopulateOptions()
            {
                List<CheckboxOption> results = await _context.CheckboxOptions.ToListAsync();
                List<SelectListItem> items = new List<SelectListItem>();
    
                foreach (CheckboxOption option in results)
                {
                    items.Add(new SelectListItem() { 
                        Value = option.Id.ToString(),
                        Text = option.Name
                    });
                }
                return items;
            }   
        }
    }
    
        public class CheckboxOption
        {
            public int Id { get; set; }
            public string? Name { get; set; }
        }
    

    The tutorials on this site also specifically illustrates how to handle dynamic checkboxes.

    Razor Pages with Entity Framework Core in ASP.NET Core - Tutorial 1 of 8

    1 person found this answer helpful.
    0 comments No comments

  2. Xinran Shen - MSFT 2,091 Reputation points
    2023-05-15T03:21:45.7766667+00:00

    Hi @Ahmed Salah Abed Elaziz ,

    If you want to get the value of the checkbox which is not be checked, you can put the state and value into one model, Please refer to this simple dmeo.

    public class MODULECODE
        {
            public int value { get; set; }
            public bool isChecked { get; set; }
        }
    
    public class UserAccess
        {
            public int UserId { get; set; }
            public List<MODULECODE> modulecode { get; set; } = new List<MODULECODE>();
        }
    

    Page Model

    [BindProperty]

    public List<Result> result { get; set; } = new List<Result>();

    View

    @page
    @model PrivacyModel
    @Html.AntiForgeryToken()
    <form method="post">
        <button type="submit" class="col-sm-1 btn btn-primary">Submit</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" 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>
    
        <div>
            <input id="StockTake" type="checkbox">
            <input name="useraccess.modulecode[0].isChecked" value="false" type="hidden" />
            <input name="useraccess.modulecode[0].value" type="hidden" value="1"/>
            <label for="lblstocktake">stock take</label>
        </div>
    
        <div>
            <input id="ShelfLabelPrint" type="checkbox">
            <input name="useraccess.modulecode[1].isChecked" value="false" type="hidden" />
            <input name="useraccess.modulecode[1].value" type="hidden" value="2" />
            <label for="lblshelflabel">shelf label print</label>
        </div>
    
        <div>
            <input id="Transfer" type="checkbox">
            <input name="useraccess.modulecode[2].isChecked" value="false" type="hidden" />
            <input name="useraccess.modulecode[2].value" type="hidden" value="3" />
            <label for="lbltransfer" style="margin-right:5px;">transfer</label>
        </div>
    </form>
    
    
    @section Scripts{
        <script>
            $(document).ready(function () {
                $('#StockTake').change(function () {
                    var isChecked = $(this).is(':checked');
                    
                    $('input[name="useraccess.modulecode[0].isChecked"]').val(isChecked);
                });
    
                $('#ShelfLabelPrint').change(function () {
                    var isChecked = $(this).is(':checked');
                    $('input[name="useraccess.modulecode[1].isChecked"]').val(isChecked);
                });
    
                $('#Transfer').change(function () {
                    var isChecked = $(this).is(':checked');
                    $('input[name="useraccess.modulecode[2].isChecked"]').val(isChecked);
                });
            });
        </script>
    
        
    }
    

    Gif Demo

    515


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Xinran Shen

    0 comments No comments

  3. Bruce (SqlWork.com) 61,731 Reputation points
    2023-05-15T15:52:07.6133333+00:00

    you can remove the javascript code from above by using asp-for checkbox binding (also don't need hidden ischecked as you are binding the checkbox)

    <input id="StockTake_0" type="checkbox" asp-for="UserAccess.MODULECODE[0].isChecked">
    <input name="UserAccess.MODULECODE[0].value" type="hidden" value="1"/>
    <label for="StockTake_0">stock take</label>
      
    
    0 comments No comments