0

I'm developing a website that can be used by users with two roles: an admin and a professor, now a professor can teach a Course, I've already set up the relationships between tables and it works fine, now when adding a course, i need to have a drop List of users(with the role of professor) so i can assign a professor to the course added, so how can i fill the drop down list with users who have the role Professor ? Here's my code for now:

 public class CreateModel : PageModel
    {
        private readonly DotNetProject.Data.ApplicationDbContext _context;
        private readonly UserManager<IdentityUser> _userManager;

        public CreateModel(DotNetProject.Data.ApplicationDbContext context, UserManager<IdentityUser> userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public IActionResult OnGet()
        {
        ViewData["BranchIdBranch"] = new SelectList(_context.Branch, "IdBranch", "IdBranch");
        ViewData["UserId"] = new SelectList(_context.AppUser, "Id", "Id");
            return Page();
        }

        [BindProperty]
        public Course Course { get; set; }


        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Course.Add(Course);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
    }

2 Answers2

0

You can find a similar question here: Get list of users with assigned roles in asp.net identity 2.0

You can pass the value to razor page using ViewBag:

ViewBag.CustomerId = new SelectList(db.Users.Where(x=> x.Roles.Where(p=>roles.Contains(p.RoleId))).Select(user=> new SelectListItem{Text=user.UserName,Value=user.UserID.ToString()}));
Nikita Fedorov
  • 790
  • 1
  • 12
  • 40
0

You can use this code :

  public void OnGet()
        {
            ViewData["ProfessorData"] =  _context.Users.Where(x => x.Roles.Select(p => p.Id).Contains(roleId)).Select(n => new SelectListItem
            {
               Value = n.Id.ToString(),
               Text = n.UserName.ToString()
            }).ToList(); 
        }

View:

   <select asp-items="@((List<SelectListItem>)ViewData["ProfessorData"])">
        <option value="">---Choose One---</option>
    </select>
LouraQ
  • 6,443
  • 2
  • 6
  • 16