3

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.

2

3 Answers 3

4

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])
}
Sign up to request clarification or add additional context in comments.

8 Comments

Isn`t there any more elegant way of doing this? I rather want it to be dynamic and not hard coded
@user281180 if you want to use the strongly typed CheckBoxFor you need a viewmodel with bool properties
any other means of achieveing the above using a more elegant method? I might not be using CheckBoxFor?
@user281180 do you try to achieve something like here? : mrgsp.md:8080/awesome/user (click on edit after on the button near roles)
Not really, I want to display all the Roles and if UserRoles contains any ofthe Role, the checkbox is checked
|
2

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?

Comments

0

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

Difficulty in filling list while comparing arrays

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.