I have user edit problem in my Edit actions.. when it comes to departmentDropdownlist When I click a user to edit let say he/she belongs to administration, I want then show administration in dropdownlist and offcourse below that all departments in the same dropdownlist. But right now when I click Edit It shows me all departments in Id order.. like I want to add a new user. I have role dropdown list. tha's woking fine. If the user is Employee .. it shows me first Employee then the rest of Role list.. If the user is Admin , then it shows me Admin then below that the rest of role list. But when it comes to department it shows me the first departmentname which DeptId = 1 and so on. I tried in both Asp.Net Mvc and Core. Here is my EditUser and EditUserViewModel
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
model.DepartmentNames = context.Departments.Select(s => new SelectListItem
{
Text = s.DeptName,
Value = s.DeptId.ToString()
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
model.DeptId = context.Departments.Single(r => r.DeptName == context.Sites.....??????); //How to do here
// ViewBag.DeptId = new SelectList(context.Departments, "DeptId", "DeptName", model.DeptId); // Even like this , shows the first id departmentname
}
}
return PartialView("_EditUser", model);
}
My EditUserViewModel
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
public string ApplicationRoleId { get; set; }
public List<SelectListItem> DepartmentNames { get; set; }
public int DeptId { get; set; } // I have DeptId too in my AspNetUser table
}
Since the User
table has DepartmentId
, I don't know why you don't assign model.DeptId
to it.
So instead of
model.DeptId = context.Departments.Single(r => r.DeptName == context.Sites.....??????);
You can just assign the DepartmentId
from the user table, i.e.,
model.DeptId = user.DepartmentId;
On Razor when you build the dropdown using TagHelper
, it should select the correct dropdown option value based on the id.
<select class="form-control" asp-for="DeptId" asp-items="DepartmentNames"></select>