0

In my application I want to enable the user to add other users to a single role. Therefore my model contains a IDictionary<string, IEnumerable<string>> where the key is the name of the role and value is the list of user-names that will be set to the given role.

However, I'm struggling on how to post this (or event how to create the hidden fields in my form) so I can access the dictionary inside my action.

This article seem to address an related issue but I did not get it managed to post the correct data.

Currently my code looks something like this:

foreach (var roleToUserRelation in Model.RoleUserRelations)
{
    @Html.Hidden(Html.NameFor(m => m.RoleUserRelations) + ".Index", s)
    @Html.HiddenFor(m => m.RoleUserRelations[s]);

    // loop through each user
    foreach (var userName in roleToUserRelation.Value)
    {
        // get the list somehow rendered to be posted as value for the dictionary
        @Html.Hidden(m => userName)
    }
}

Is it possible to do it this way or should I re-think the model-structure in order to avoid the usage of a dictionary here?

Community
  • 1
  • 1
KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • You cannot use a `foreach` loop to generate form controls for a collection (refer [this answer](https://dotnetfiddle.net/5ewluv)) and using a dictionary is the worst type to use in a view. Just use a view model with a `IList` proeprty –  Jun 21 '16 at 12:04
  • But since you have only shown hidden inputs, what is the point of this? –  Jun 21 '16 at 12:05
  • The values are set via `Javascript`, so hidden fields are good enough for this scenario and it's more about how the naming should be in order to make the model-binder work as needed – KingKerosin Jun 21 '16 at 12:08
  • @StephenMuecke How would using a `IList` help? How would I know where the list belongs to (to which role)? Even the roles are some kind of dynamic, and therefore a list per role is not feasible. – KingKerosin Jun 21 '16 at 12:14
  • Use a view model to represent what you want to display and edit. Impossible to tell from what you have posted, but best guess is you want it to have a property `string Role` and `List Users` and then the view would be a `@model List`. But using hidden inputs makes no sense if your wanting users to edit something –  Jun 21 '16 at 12:19

1 Answers1

0

You should use a checkboxlist which will be users and Role name should be in hidden field. On form post you can get all checked checkbox. Your model should have 2 property one for collection of username and other will be RoleName. When you will post form mvc will automatically bind the model.

If you have any doubt feel free to ask me.

If i helped mark this post as answer

Seach for how to create checkbox list it is very easy you just need to put all checkbox in a single group name.

Sandip Jaiswal
  • 3,428
  • 2
  • 13
  • 15