Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,
I currently have this working I have a submit button currently being used to assign roles. I have a second button to remove the roles. To remove the roles I call an $.ajax call and I pass my controller with the id to my action. This works BUT my TempData[msg] isn’t being stored so when the call finishes no message is displayed like when I add a role. Also the Roles are not being refreshed with my ‘return redirectToAction()’ at the end of my action method.
Here is what I have is there a way I can get those small things working or what are some more ideas to do this?
Thank you,
C#
//VIEW This is where I am getting my userId from this DropDownList @Html.AntiForgeryToken()

            <div class="row">
                <div class="col-md-4">
                    @Html.DropDownListFor(a => a.UserId,
                     new SelectList(Model.lstAdmins, "UserId", "Name"),
                     new { @class = "form-control", @id = "userAdmins" })
                    @* , @onChange = "SelectedValue(this)"*@
                    @Html.HiddenFor(a => a.UserId)
                    @Html.ValidationMessageFor(a => a.UserId)
                </div>
                <div class="col-md-4"></div>
                <div class="col-md-4"></div>
            </div><div class="row">
                @for(var i = 0; i < Model.lstUsers.Count(); i++)
                {
                    <div class="col-md-4">
                        <div>
                            @Html.CheckBoxFor(u => Model.lstUsers[i].SelectedUsers)
                            <label>
                                @Html.DisplayFor(u => Model.lstUsers[i].Name)
                                @Html.HiddenFor(u => Model.lstUsers[i].UserId)
                                @Html.HiddenFor(u => Model.lstUsers[i].Name)
                            </label>
                        </div>
                    </div>
                }
            </div>
            <br />
            <div class="row">
                <div class="form-group">
                    <div class="col-md-offset-0 col-md-12">
                        <input type="submit" value="Assign Role" class="btn btn-success" />
                        @* @Url.Action("RemoveAdmin", "SuperAdmin") *@

                        <button type="button" onclick="clickMe()"
                                class="btn btn-danger">
                            Remove Role
                        </button>

                        @Html.ActionLink("Cancel", "Dashboard", "SuperAdmin",
                         null, new { @class = "btn btn-danger" })
                    </div>                                                          <script type="text/javascript">
    //$(function () {

    function clickMe() {
        var userid = $("#userAdmins").val();
        if (userid != "") {
            $.ajax({
                url: "RemoveAdmin/SuperAdmin",
                data: { userid: userid },
                type: "POST",
                //success: function () {
                //    alert("Success");
                //},
                //error: function () {
                //    alert("Error");
                //}
            });
        }
        //window.location.href =
            //'Url.Action("RemoveAdmin", "SuperAdmin")/' + userid;
        //alert("val" + selectedValue);
    }
// CONTROLLER ACTION
[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult RemoveAdmin(string userid)
        {
            ApplicationUser au = context.Users.Where(u => u.Id.Equals(userid,
                StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);
            manager.RemoveFromRole(au.Id, "Admin");
            manager.AddToRole(au.Id, "User");

            TempData["Success"] = "Roles Assigned Successfully";
            return RedirectToAction("AssignAdmin");
        }


What I have tried:

I used my controller to create a action to addusers to a role that works without any issses and I have 2 methods that gets all the current users with there certain roles. I want this to call my uses so it can display the correct users ether in the dropdown if they are admin or in the lstUsers if they are a normal user. I used javascript to get the value and aajax to make the call but its not working 100% how I want
Posted
Updated 4-Apr-19 3:53am

(The way I'd do it) Instead of having two buttons, use a checkbox to indicate whether the user does or does not have the role, and have a single submit button.
 
Share this answer
 
You're making an AJAX request, and doing nothing with the response.

Change your action to return just the redirection URL if the request is an AJAX request:
C#
[HttpPost]
public ActionResult RemoveAdmin(string userid)
{
    ...
    
    TempData["Success"] = "Roles Assigned Successfully";
    if (Request.IsAjaxRequest()) return Json(Url.Action("AssignAdmin"));
    return RedirectToAction("AssignAdmin");
}

Then change your Javascript code so that it navigates to the returned URL when the AJAX request succeeds:
JavaScript
$.ajax({
    url: "RemoveAdmin/SuperAdmin",
    data: { userid: userid },
    type: "POST",
    success: function(result) {
        window.location.assign(result);
    }
});
 
Share this answer
 
Comments
TheBigBearNow 4-Apr-19 18:49pm    
This almost solved my problem I feel but it still didnt work.. My project does not refresh on the button click + tempdata msg dont display. Here is my code.
[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult RemoveAdmin(string userid)
        {
            ApplicationUser au = context.Users.Where(u => u.Id.Equals(userid,
                StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);
            
            manager.RemoveFromRole(au.Id, "Admin");
            manager.AddToRole(au.Id, "User");
            if (Request.IsAjaxRequest())
            {
                TempData["SuccessRole"] = "Role Removed Successfully";
                Json(Url.Action("AssignAdmin"));
                return RedirectToAction("AssignAdmin", "SuperAdmin");
            }
            
            //TempData["Success"] = "Roles Assigned Successfully";
            return RedirectToAction("AssignAdmin");
        }
 function clickMe() {
        var userid = $("#userAdmins").val();
        if (userid != "") {
            $.ajax({
                url: "RemoveAdmin/SuperAdmin",
                data: {
                    userid: userid
                },
                type: "POST",
                success: function (result) {
                    window.location.assign(result);
                }
                //error: function () {
                //    alert("Error");
                //}
            });
Richard Deeming 5-Apr-19 7:22am    
You forgot to return the JSON response for an AJAX request:
[HttpPost]
public ActionResult RemoveAdmin(string userid)
{
    ApplicationUser au = context.Users.Where(u => u.Id.Equals(userid, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
    var store = new UserStore<ApplicationUser>(context);
    var manager = new UserManager<ApplicationUser>(store);
    
    manager.RemoveFromRole(au.Id, "Admin");
    manager.AddToRole(au.Id, "User");
    
    TempData["SuccessRole"] = "Role Removed Successfully";
    if (Request.IsAjaxRequest()) return Json(Url.Action("AssignAdmin", "SuperAdmin"));
    return RedirectToAction("AssignAdmin", "SuperAdmin");
}

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