Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try to add my user to role but its not working .

What I have tried:

C#
[BindProperty]
public MyUser MyUser { get; set; }
public async Task<IActionResult> OnPostAsync(string  id, UserManager<MyUser>role)
{

    if (id == null)
    {
        return NotFound();
    }

    MyUser = await _context.Users.FirstOrDefaultAsync(e => e.Id == id);


  
    var userId = _userManager.GetUserId(User);

    var user = await _context.Users
      .Where(u => u.Id == userId)
      .FirstOrDefaultAsync();
    

    await role.AddToRoleAsync(user, "admin");
    await _context.SaveChangesAsync();
   


    return Page();
}
Razor
<tbody>
    @foreach (var item in Model.MyUser)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                <form method="post">
                    <a asp-page=""><input type="submit" class="btn btn-primary" value="Add Role" /></a>
                </form>
            </td>
        </tr>
    }
</tbody>
Posted
Updated 6-Apr-21 6:36am
v2

The foreach block in your view makes no sense - why would a class representing a single user implement IEnumerable<???>?

But the problem appears to be in your action:
C#
// Find the user with the specified ID, and store it in the MyUser property:
MyUser = await _context.Users.FirstOrDefaultAsync(e => e.Id == id);

// Find the ID of **THE CURRENT USER**:
var userId = _userManager.GetUserId(User);

// Find the user with the same ID as **THE CURRENT USER**:
var user = await _context.Users.Where(u => u.Id == userId).FirstOrDefaultAsync();

// Add **THE CURRENT USER** to the admin role:
await role.AddToRoleAsync(user, "admin");
That should simply be:
C#
// Find the user with the specified ID:
var user = await _context.Users.FirstOrDefaultAsync(e => e.Id == id);

// Add that user to the admin role:
await role.AddToRoleAsync(user, "admin");
await _context.SaveChangesAsync();
 
Share this answer
 
Comments
Banana Life 6-Apr-21 12:29pm    
Thank you for your answer
its not single user ,i use foreach to show all users for super admin and super admin can add user to admin role. First i try with button but i want change to checkbox later
ASP.NET
//this is my view users list(IEnumerable)for super admin  

 public IList<MyUser> MyUser { get; set; }


       
        public async Task<IActionResult> OnGetAsync()
        {
          

           MyUser = await _context.Users.ToListAsync();

            return Page();
        }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900