Using CheckBoxFor

I have 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 this: I want to check the box for each role, and if Role == userRoles, the checkbox is true else false. How can I use @ HTml.CheckboxFor ... Can I get an example.

+3
source share
3 answers

You are going to peel off with hard-coded values ​​if you are trying to create a list of flags based on data from the database.

You can try something like my CheckBoxListFor <> extension:

How to create CheckBoxListFor validation method in ASP.NET MVC?

+2
source

to use CheckBoxFor you need a ViewModel with bool properties

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

and in view

@model YourVM

@for (int i = 0; i < Model.Roles.Count(); i++) {
@Html.CheckBoxFor(m => m.Roles[i])
}
+4
source

I answered this and your other question, on your other question. There is no reason to ask several questions on the same problem, you can edit your own questions.

Difficulty filling the list when comparing arrays

0
source

Source: https://habr.com/ru/post/1787929/


All Articles