简体   繁体   中英

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.

在此输入图像描述

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"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM