I have this “problem” that i have code like this in many of my controller actions:
var users = new List<SelectListItem>();
foreach(var user in userRepository.GetAll())
{
var item = new SelectListItem { Text = user.FriendlyName, Value = user.UserId.ToString() };
if (User.Identity.Name == user.UserName)
item.Selected = true;
users.Add(item);
}
ViewData["Users"] = users;
How would you refactor this to a more clean solution? I want to get DRY!
I would create this to be an extension method applied to
List<user>or whatever your userRepository.GetAll() returns so then in your code you can replace all of these usages with justEdit code sample: There’s 2 ways you could do this
And usage would be like
Or if you have problems with identity being in the extension method have
And usage would be like