1

I have two classes in a model, see below:

public class Action
{
    public int Id { get; set; }
    public bool HasChecked { get; set; }
}

public class Function
{
    public int Id { get; set; }
    public IEnumerable<Action> Actions { get; set; }
}

public class Permission
{
    public int Id { get; set; }
    public IEnumerable<Function> Functions { get; set; }
}

I want to know what is the best option to use CheckBox in chstml, since I have a Permission model to viewModel. Is it possible to return the typed collection to the controller? (Permisson has many Functions with many actions)

Thanks!

1 Answer 1

1

You definitely can do this. I believe the model will need to be a Collection or List or the like rather than IEnumerable (I could be mistaken on that, but I've only ever used Lists).

The easiest way to go after that is in your view, you iterate over each collection of stuff, and spit out a checkbox for each action like so:

@if (Model != null && Model.Functions != null)
{
   for (int i = 0; i < Model.Functions.Count; i++)
   {
      var fcn = Model.Functions[i];
      for (int j = 0; j < fcn.Actions.Count; j++)
      {
          @Html.CheckboxFor(model => Model.Functions[i].Actions[j].HasChecked);
          @Html.DisplayFor(model => fcn.Actions[j]);
      }
   }
 }

Been a while since I've done it, but I think something along those lines should work for you. If you want to do it in HTML yourself, the main thing you want to pay attention to is that the name attribute of your inputs should look something like name=Functions[0].Actions[1].HasChecked (for the second action of the first function of the model).

Sign up to request clarification or add additional context in comments.

3 Comments

Great. Now is clear for me, but how post the name=Functions[0].Actions[1].HasChecked collection typed to the controller? is it possible or model binder will take care with string[]? Thanks
The modelbinder will take care of it if you're taking in a Permission type (based on your models listed) to your action method. ModelBinder doesn't handle string[] unless you create a custom one.
Also, it's worth pointing out that my syntax for the name attribute is what the *For() helpers generate for you, so you don't need to do that if you're using them.

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.