I’m trying to “convert” this into a strongly typed model instead of ViewData. But how should that look?
I got this in my controller:
public ActionResult UserEdit(int? userID)
{
User u;
if (userID == null)
{
u = new User();
}
else
{
u = _us.GetUsers(userID.Value).First();
u.Usergroups.Load();
}
List<int> selectedUsergroupIDs = new List<int>();
foreach (Usergroup item in u.Usergroups)
{
selectedUsergroupIDs.Add(item.UsergroupID);
}
MultiSelectList UsergroupID = new MultiSelectList(_ug.GetUsergroups(), "UsergroupID", "UsergroupName", selectedUsergroupIDs);
ViewData["UsergroupID"] = UsergroupID;
return View("UserEdit", new UserAdminEditViewModel { User = u, Usergroups = _ug.GetUsergroups() });
}
“UsergroupID” in this case, what’s needed to add in my model and in my view?
Thanks in advance
/M
Not sure I understand the entire question, but if you’re asking what can you do to make this model usable in the page, make sure the page inherits from
ViewPage<UserAdminEditViewModel>.Also, the MultiSelectList class has both the selected and unselected values so you don’t need to have both of them in the view model so you can pair them down to a single member of the model. You’ll need to change
UserAdminEditViewModelto look something like this.At the end of your controller:
Then, in your view page:
Also, note that you’re invoking _ug.GetUsergroups() twice. That should go away with this solution but if you still need to reference it I’d recommend caching it within the action if you’re not caching it in the method call itself so you don’t hit the database every time you need the list.
I think this answers your question. If not, please clarify. Also, I haven’t tested this code so it’s not guaranteed to compile but it should work.