Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using CheckBoxFor

I am having a class Role as follows;

public enum Role
{                                            
    User1 = 1,
    User2 = 2,
    User3 = 3, 
    User4 = 4
}

I have the following codes in my model

public Role[] UserRoles { get; set; }
 User user = User.Load(1);
        UserRoles = user.Roles;

My question is as follows: I want to have a checkbox for each Role and if Role == userRoles, the checkbox is true else false. How can I use @HTml.CheckboxFor...Can I have an example please.

like image 540
learning Avatar asked Dec 14 '25 09:12

learning


2 Answers

to use the CheckBoxFor you need a ViewModel with bool properties

public class YourVM
{                                            
  public bool[] Roles {get;set;}
}

and in the view

@model YourVM

@for (int i = 0; i < Model.Roles.Count(); i++) {
@Html.CheckBoxFor(m => m.Roles[i])
}
like image 58
Omu Avatar answered Dec 16 '25 21:12

Omu


You're going to come unstuck with hard-coded values if you are trying to create a checkbox list based on data from a DB.

You could try something like my CheckBoxListFor<> Extension:

How to create a CheckBoxListFor extension method in ASP.NET MVC?

like image 38
Rob Avatar answered Dec 16 '25 23:12

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!