Search code examples
c#asp.net-mvcasp.net-roles

How do I perform 2 different ActionResults in the same controller within the same view?


I am trying to remove a role from my application user on ActionLink click and when it is successful send a Viewbag message. The issue I am having currently is that when I try to remove the user from the role, the page is being refreshed. The reason for this is because I want the admin to be able to get a list of roles he is requesting and delete from the same page, to keep the application lean. Here is my controller action:

public ActionResult DeleteRoleForUser()
{
    var list = _context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
    ViewBag.Roles = list;
    return RedirectToAction("GetRoles");
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteRoleForUser(string UserName, string RoleName)
{
    var account = new AccountController();
    ApplicationUser user = _context.Users.FirstOrDefault(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));

    if (account.UserManager.IsInRole(user.Id, RoleName))
    {
        account.UserManager.RemoveFromRole(user.Id, RoleName);
        ViewBag.Message = "Role removed from this user successfully!";
        return View("GetRoles");
    }
    var list = _context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
    ViewBag.Roles = list;

    return View("GetRoles");
}

Here is the remove link on my view

@Html.ActionLink("Remove Role", "DeleteRoleForUser", new{controller = "Role"})

I have the DeleteRoleForUser and the GetRoles controllers working properly/separately on different views by themselves with DeleteRoleForUser using a listbox to display all roles in the database, however, as I mentioned earlier I would like to combine the two pieces of functionality.

enter image description here


Solution

  • First, your action link will cause your browser to issue a GET request, not a POST. So your [HttpPost] attribute will need to change accordingly.

    Second, you aren't passing in any parameters into the method. Your link will need to change to

    @Html.ActionLink("Remove Role", "DeleteRoleForUser", new{ controller = "Role", UserName="username", RoleName="role"})