Simsons
Simsons

Reputation: 12745

MultiselectList with selected values are not pre selected in View

I have a simple service which is : 1. Getting All roles in a system 2. Check the role of current selected user 3. Render all roles in a dropdown , selecting current user roles by default

To do that , I have following code:

 public ActionResult Edit(string userId)
        {

            var user = _oAuthUserService.GetUsers()?.Where(u => u.UserId == userId).FirstOrDefault();

            var userRoles = user.Roles; //[Admin,Manager]

            var allRolesFromService = _oAuthUserService.AllRoles.Select(x=>new {
                Id =x.RoleName,
                Name =x.RoleName
            }).ToList(); //All roles in the System [Role1,Role2,Role3,Admin,Manager]


            ViewData["AllRoles"] = new MultiSelectList(allRolesFromService, "Id", "Name", userRoles);


            return View(user);


        }

In view I am doing ,

@Html.ListBox("AllRoles", (MultiSelectList)ViewData["AllRoles"], new { multiple = "multiple" });

But when I navigate to view , none of the items are pre-selected? What am I missing here?

Upvotes: 0

Views: 546

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

The problem occurs because you're using same ViewData key name as model name bound to ListBox helper in this line:

@Html.ListBox("AllRoles", (MultiSelectList)ViewData["AllRoles"], new { multiple = "multiple" })

Assumed that AllRoles is an array or list property inside viewmodel class, you can't reuse it as ViewData key name because naming collision will happen between them, causing the option lists won't show up properly. You can rename ViewData key name with any different name than viewmodel's property name:

ViewData["AllRolesList"] = new MultiSelectList(allRolesFromService, "Id", "Name", userRoles);

And then use new key name within ListBox(For) helper:

ListBox helper

@Html.ListBox("AllRoles", (MultiSelectList)ViewData["AllRolesList"], new { multiple = "multiple" })

ListBoxFor helper

@Html.ListBoxFor(model => model.AllRoles, (MultiSelectList)ViewData["AllRolesList"], new { multiple = "multiple" })

Upvotes: 1

Related Questions