Dynamic Checkbox list in Razor Pages

Blooming Developer 276 Reputation points
2023-11-15T03:52:47.2633333+00:00

Hi,

I need to display my checkbox value dynamically from a database stored value in Razor pages.

The scenario is i have a Customers table and Users table. When i am adding a new user, i need to give access to some customers using checkbox list. In order to handle this i have created a AccessRights table also. Please find my Models below

UserManagement.Cs

public class UserManagement
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Please Enter Username")]
        [Display(Name = "Username")]
        public string Username { get; set; }

        [Required(ErrorMessage = "Please Enter Name")]
        [Display(Name = "Name")]
        public string Name { get; set; }

        [Required(ErrorMessage = "Please Enter Email Address")]
        [Display(Name = "Email Address")]
        [EmailAddress(ErrorMessage = "Invalid Email Address.")]
        public string EmailAddress { get; set; }

        [Required(ErrorMessage = "Please Select Userrole")]
        [Display(Name = "Userrole")]
        public string Userrole { get; set; }

        [Required(ErrorMessage = "Please Select Status")]
        [Display(Name = "Status")]
        public string Status { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? CreatedTimeStamp { get; set; }
        public string LastModifiedBy { get; set; }
        public DateTime? LastModifiedTimeStamp { get; set; }
    }


Customer.Cs

public class Customer
    {
        [Key]
        public int Id { get; set; }

        [Required(ErrorMessage = "Please Enter Customer Name")]
        [Display(Name = "Customer Name")]
        public string CustomerName { get; set; }        

        [Required(ErrorMessage = "Please Select Status")]
        [Display(Name = "Status")]
        public string Status { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? CreatedTimeStamp { get; set; }
        public string LastModifiedBy { get; set; }
        public DateTime? LastModifiedTimeStamp { get; set; }

    }


AccessRights.Cs

public class AccessRights
    {
        [Key]
        public int Id { get; set; }
        public int EmployeeId { get; set; }        
        public string Username { get; set; }
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string CreatedBy { get; set; }
        public DateTime? CreatedTimeStamp { get; set; }
        public string LastModifiedBy { get; set; }
        public DateTime? LastModifiedTimeStamp { get; set; }
    }



When i create a new user, i want to insert the checked customer details to the AccessRights table. But i am not able to display the Customer name in a checkboxlist.

Please find Create User screen below.

<form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="UserManagement.Username" class="control-label"></label>
                <input asp-for="UserManagement.Username" class="form-control" />
                <span asp-validation-for="UserManagement.Username" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="UserManagement.Name" class="control-label"></label>
                <input asp-for="UserManagement.Name" class="form-control" />
                <span asp-validation-for="UserManagement.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="UserManagement.EmailAddress" class="control-label"></label>
                <input asp-for="UserManagement.EmailAddress" class="form-control" />
                <span asp-validation-for="UserManagement.EmailAddress" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="UserManagement.Userrole" class="control-label"></label>
                <select asp-for="UserManagement.Userrole" asp-items="@Model.UserRoleList" class="form-control">
                    <option value="">Please Select</option>
                </select>
                <span asp-validation-for="UserManagement.Userrole" class="text-danger"></span>
            </div>
            
            <div class="form-group">
                <label  class="control-label"> Access To Customers</label>
                <div class="checkbox checkboxlist">
                    @{
                            foreach(int i=0; i < Model.CustomerList.Count(); i++)
                            {
                                <input asp-for="@Model.CustomerList[i].Id" type="checkbox" />
                                <label asp-for="@Model.CustomerList[i].Id">@Model.CustomerList[i].CustomerName</label>
                                <input asp-for="@Model.CustomerList[i].Id" type="hidden" />
                                <input asp-for="@Model.CustomerList[i].CustomerName" type="hidden" />
                            }
                        }
                </div>
                <span  class="text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="UserManagement.Status" class="control-label"></label>
                @foreach (var UserStatus in Model.status)
                {
                    <input type="radio" class="form-check-inline" style="margin-left:2px;" asp-for="UserManagement.Status" value="@UserStatus" />
                    @UserStatus
                }<br/>
                <span asp-validation-for="UserManagement.Status" class="text-danger"></span>
            </div>
            <div class="form-group" style="display:none;">
                <label asp-for="UserManagement.LastModifiedBy" class="control-label"></label>
                <input asp-for="UserManagement.LastModifiedBy" class="form-control" />
                <span asp-validation-for="UserManagement.LastModifiedBy" class="text-danger"></span>
            </div>
            <div class="form-group" style="display:none;">
                <label asp-for="UserManagement.LastModifiedTimeStamp" class="control-label"></label>
                <input asp-for="UserManagement.LastModifiedTimeStamp" class="form-control" />
                <span asp-validation-for="UserManagement.LastModifiedTimeStamp" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>

CreateUser.Cshtml.Cs

public class CreateModel : PageModel
    {
        private readonly Kallang_Attendance_Dashboard.Data.Kallang_Attendance_DashboardContext _context;

        public CreateModel(Kallang_Attendance_Dashboard.Data.Kallang_Attendance_DashboardContext context)
        {
            _context = context;
        }

        [BindProperty]
        public UserManagement UserManagement { get; set; }

        [BindProperty]
        public Roles Roles { get; set; }

        public SelectList UserRoleList { get; set; }
        public string[] status = new[] { "Active", "InActive" };

        [BindProperty]
        public List<Customer> CustomerList { get; set; }
        public IActionResult OnGet()
        {
            if (HttpContext.Session.GetString("UserRole") != "Admin")
            {
                TempData["Unauthorize"] = "Unauthorize";
                return RedirectToPage("/Login");
            }
            UserRoleList = new SelectList(_context.Roles.OrderBy(e => e.Id), "UserRole", "UserRole");
            CustomerList = new List<Customer>();
            CustomerList = (from customer in _context.Customer
                            select customer).ToList();
            return Page();
        }

        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        {
            UserRoleList = new SelectList(_context.Roles.OrderBy(e => e.Id), "UserRole", "UserRole");
            var UserExists = await _context.UserManagement.FirstOrDefaultAsync(m => m.Username == UserManagement.Username);
            if (UserExists != null)
            {
                TempData["UserExists"] = "Exists";
                return Page();
            }
            UserManagement.CreatedBy = HttpContext.Session.GetString("DisplayName").Trim();
            UserManagement.CreatedTimeStamp = DateTime.Now;
            UserManagement.LastModifiedBy = HttpContext.Session.GetString("DisplayName").Trim();
            UserManagement.LastModifiedTimeStamp = DateTime.Now;

            _context.UserManagement.Add(UserManagement);
            await _context.SaveChangesAsync();
            TempData["UserCreated"] = "UserCreated";

            return RedirectToPage("./Index");
        }
    }


I am stuck on this part.Could someone guide me please?

Hi @Zhi Lv - MSFT , @Jerry Cai-MSFT , Appreciate your help on this.

Thanks,

Teena

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