I want users to be able to select multiple skills from a MultiSelectList dropdown. I am able to save the multiple skill selections of each user to the database, but I discovered if I remove a skill option for one user, and I log in with a different user who previously had the same skill saved in his selections, it would have been removed for this user and every other user that had similar skill option saved.
Just so I am being clear. Let's say user A had these skills saved ["C#", "Python", "Java"]. User B current currently saved skills are ["C++","Scala"]. User B then logs and decides to add the C# he has just learnt. Once he updates his profile and his selections become this ["C++","Scala", "C#"]. C# would have been removed from User A's selections so it becomes ["Python", "Java"].
This is my custom IdentityUser
class.
public class ApplicationUser : IdentityUser
{
public ApplicationUser()
{
Skills = new List<Skill>();
}
public string Location { get; set; }
public virtual ICollection<Skill> Skills { get; set; }
}
This is the Skill model.
public class Skill
{
public int SkillId { get; set; }
public string SkillType { get; set; }
}
And this is how I save the skill selections in the controller.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Profile(ProfileViewModel profileModel)
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
if (ModelState.IsValid)
{
if (user.Location != profileModel.Location) user.Location = profileModel.Location;
if (profileModel.SelectedSkillIds != null)
{
List<Skill> tempSkills = new List<Skill> { };
foreach (var skillID in profileModel.SelectedSkillIds)
{
user.Skills.Add(_context.Skills.FirstOrDefault(x => x.SkillId == skillID));
var skill = _context.Skills.Find(skillID);
if (skill != null)
{
user.Skills.Add(skill);
tempSkills.Add(skill);
}
var allSkills = _context.Skills.ToList();
var skillsToRemove = allSkills.Except(tempSkills);
foreach (var sk in skillsToRemove)
{
user.Skills.Remove(sk);
}
}
await _userManager.UpdateAsync(user);
await _signInManager.RefreshSignInAsync(user);
return RedirectToAction("Profile", "Account");
}
return View(profileModel);
}
}
Update - How I delete selections
if (profileModel.SelectedSkillIds != null)
{
List<UserSkill> tempSkills = new List<UserSkill> { };
foreach (var skillID in profileModel.SelectedSkillIds)
{
var skill = _context.Skills.Find(skillID);
if (skill != null)
{
var userskill = new UserSkill { AppUserId = user.Id, SkillId = skill.SkillId };
user.UserSkills.Add(userskill);
tempSkills.Add(userskill);
}
var allSkills = _context.UserSkills.ToList();
var skillsToRemove = allSkills.Except(tempSkills);
foreach (var sk in skillsToRemove)
{
user.UserSkills.Remove(sk);
}
}