How to get which checkbox have check true or false on razor page mvc ?

Ahmed Salah Abed Elaziz 390 Reputation points
2023-05-11T13:03:23.8733333+00:00

I working on asp.net core MVC razor page . I face issue I can't get checkbox checked or not on page model razor page .

so which checkbox have checked or not checked this is exactly I need to get on page model MVC.

so if checkboxes StockTake and ShelfLabelPrint checked so I will get value 1 and 2 is true on page model .

checkbox Transfer not checked so it will get value 3 status false .

public class AddUserAccessModel : PageModel
    {
        [BindProperty]
        public UC.ADC.Core.Entities.SQL.UserAccess UserAccess { get; set; }
public async Task OnPost(UC.ADC.Core.Entities.SQL.UserAccess useraccess)
        {
       string[] checkedModuleCodes = Request.Form["checks"];
      // How to recognize which check box have checked or not here
        }
    }

ON AddUserAccess.cshtml Razor view

@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>
    <input id="StockTake" name="checks" type="checkbox" asp-for="UserAccess.MODULECODE" value="1">
        <label for="lblStockTake">Stock Take</label>
    <input id="ShelfLabelPrint" name="checks" type="checkbox" asp-for="UserAccess.MODULECODE" value="2">
        <label for="lblShelfLabel">Shelf Label Print</label>

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




    </form>

expectation result I need as below

getcheckboxes checked or not

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,280 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,362 questions
0 comments No comments
{count} votes

Accepted answer
  1. AgaveJoe 26,671 Reputation points
    2023-05-12T21:28:05.3966667+00:00

    values of check boxes as 1,2,3 etc passed i need also pass status true or false per every value

    I'm rather confused by your response because if you received the 1, 2, 3 then you know 1, 2, and 3 are true. If 1 and 3 is received then you know 1 and 3 are true but 2 is false. A basic LINQ query can tell you what values exist in the collection.

    List<int> options = new List<int> { 1,3 };
    Console.WriteLine($"1 is selected {options.Any(i => i == 1)}");
    Console.WriteLine($"2 is selected {options.Any(i => i == 2)}");
    Console.WriteLine($"3 is selected {options.Any(i => i == 3)}");
    
    1 is selected True
    2 is selected False
    3 is selected True
    

    I think you have larger design issues though and going through a few Razor Page tutorials will help you move forward.


2 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,671 Reputation points
    2023-05-11T15:53:45.2866667+00:00

    You are asking a Razor Pages question not MVC! I think the code below answers your original question.

        public class UserAccess
        {
            public int UserId { get; set; } 
            public int[] checks { get; set; }
        }
    
    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    
    <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>
        <input id="StockTake" name="UserAccess.checks" type="checkbox" value="1">
        <label for="lblStockTake">Stock Take</label>
        <input id="ShelfLabelPrint" name="UserAccess.checks" type="checkbox" value="2">
        <label for="lblShelfLabel">Shelf Label Print</label>
    
        <input id="Transfer" name="UserAccess.checks" type="checkbox" value="3">
        <label for="lblTransfer" style="margin-right:5px;">Transfer</label>
    
    </form>
    
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using RazorPagesDemo.Models;
    
    namespace RazorPagesDemo.Pages
    {
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public void OnGet()
            {
    
            }
    
    
            [BindProperty]
            public UserAccess UserAccess { get; set; }
    
            public async Task OnPost(UserAccess useraccess)
            {
                UserAccess = useraccess;
            }
        }
    }
    
    0 comments No comments

  2. Bruce (SqlWork.com) 59,036 Reputation points
    2023-05-11T16:15:51.04+00:00

    when you use asp-for with a check box, it renders two elements. the checkbox and a hidden field with the asp-for name and value false. if you use asp-for you should not specify a name, or value.

    the checkbox when used with the asp-for is expected to bind to a bool. if true the post will have name=true&name=false, if false the post will have name=false.

    if you want the checkbox to behave like a text field, then do not use the asp-for. then the browser will post the value if checked, else not post the value.

    so to fix your code. remove the asp-for from the checkboxes. then Request.Form["checks"] will be a list of only the checked values.

    the other approach is to define [BindProperty] bool fields and use the asp-for to bind to them