locked
Removing role works but adding role gets a model is null in my dropdownlist RRS feed

  • Question

  • User-544325736 posted

    I have a view that has a model and in the model I have 2 List<t> that populates correctly and shows the right data in the correct spots on the view populate action. I have it so the 2 list<t> can switch roles and be on the other one for each user. When I remove a role so they go on the other list it works correctly. When I go to add a role I get a model is null but when I go into debug to check the list of the model it is null when I click the add to role btn BUT when I remove role btn it is populated. It is only happening when I reopen my view on addrole btn. It’s in the DropdownlistFor I’m thinking it has to do with a=>a.UserId here is my code for adding and re

    public ActionResult AssignAdmin()
            {
                //var lstAdmins = (from users in context.Users
                //                 from roles in users.Roles
                //                 join r in context.Roles
                //                 on roles.RoleId equals r.Id
                //                 where r.Name.Equals("Admin")
                //                 select new AssignRolesModel()
                //                 { }).ToList();
                AssignRolesModel model = new AssignRolesModel();
                model.lstAdmins = AdminList();
                model.lstUsers = UserList();
                UsersSelectList();
                RolesSelectList();
    
                return View(model);
            }
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult AssignAdmin(AssignRolesModel model)
            {
                try
                {
                    if(model.lstUsers == null)
                    {
                        TempData["Error"] = "There are no Users to Assign Roles";
                        model.lstUsers = UserList();
                        model.lstAdmins = AdminList();
                        return View(model);
                    }
    
                    var selectedUsersCount = (from user in model.lstUsers
                                              where user.SelectedUsers == true
                                              select user).Count();
                    if(selectedUsersCount == 0)
                    {
                        TempData["Error"] = "You have not Selected any User to Assign Roles";
                        model.lstAdmins = AdminList();
                        model.lstUsers = UserList();
                        return View(model);
                    }
    
                    if (ModelState.IsValid)
                    {
                        List<UserModel> users = new List<UserModel>();
                        ApplicationUser au;
                        var store = new UserStore<ApplicationUser>(context);
                        var manager = new UserManager<ApplicationUser>(store);
                        model.CreatedBy = 1;
                        
                        foreach(var u in model.lstUsers)
                        {
                            if(u.SelectedUsers == true)
                            {
                                users.Add(u);
                            }
                        }
    
                        foreach(var u in users)
                        {
                            au = context.Users.Where(x => x.Id.Equals(u.UserId,
                                StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                            manager.RemoveFromRole(au.Id, "User");
                            manager.AddToRole(au.Id, "Admin");
                        }
    
                        TempData["Success"] = "Roles Assigned Successfully";
                        return RedirectToAction("AssignAdmin");
                    }
                }
                catch (Exception)
                {
                    throw;
                }           
    
                return View();
            }
    
            [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");
    
                //AssignRolesModel model = new AssignRolesModel();
                //model.lstAdmins = AdminList();
                //model.lstUsers = UserList();
                //UsersSelectList();
                //RolesSelectList();
    
                if (Request.IsAjaxRequest())
                {
                    TempData["SuccessRole"] = "Role Removed Successfully";
                    Json(Url.Action("AssignAdmin"));
                    return RedirectToAction("AssignAdmin", "SuperAdmin");
                }
    
                //TempData["Success"] = "Roles Assigned Successfully";
                return RedirectToAction("AssignAdmin");
               // return View("AssignAdmin", model);
            } <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12">
            <div class="col-lg-6 col-md-6 col-sm-12 justify-content-center">
                <div class="panel panel-success">
                    <div class="panel-heading">Choose Administrator</div>
                    @using (Html.BeginForm("RemoveAdmin", "SuperAdmin", FormMethod.Post))
                    {
                        @Html.AntiForgeryToken()
                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-10">
                                    @Html.DropDownListFor(a => a.UserId,
                                        new SelectList(Model.lstAdmins, "UserId", "Username"),
                                        new { @class = "form-control", @id = "userAdmins" })
                                    @* , @onChange = "SelectedValue(this)"*@
                                    @Html.HiddenFor(a => a.UserId)
                                    @Html.ValidationMessageFor(a => a.UserId)
                                </div>
                            </div>
                        </div>
                        <div class="panel-footer text-center">
                            <input type="submit" value="Remove Admin Role" class="btn btn-danger" />
                        </div>
                    }
                </div>
    
                <br />
                <div class="panel panel-success text-center">
                    <div class="panel-heading">
                        Choose User to Assign | Remove Administrator Role
                    </div>
                    @using (Html.BeginForm())
                    {
                        @Html.AntiForgeryToken()
                        <div class="panel-body">
                            <div class="clearfix"></div>
                            @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].Username)
                                            @Html.HiddenFor(u => Model.lstUsers[i].UserId)
                                            @Html.HiddenFor(u => Model.lstUsers[i].Name)
                                        </label>
                                    </div>
                                </div>
                            }
                        </div>
                        <div class="panel-footer form-group">
                            <input type="submit" value="Assign Role" class="btn btn-success" />
    
                            @Html.ActionLink("Cancel", "Dashboard", "SuperAdmin",
                                                null, new { @class = "btn btn-danger" })
    
                            <button type="button" onclick="clickMe()"
                                    class="btn btn-danger">
                                Remove Role
                            </button>
                        </div>
                    }
                </div>
            </div>                                                                          public class AdminModel
        {
            public string UserId { get; set; }
            public string Name { get; set; }
            public string Username { get; set; }
        }
        public class UserModel
        {
            public string UserId { get; set; }
            public string Name { get; set; }
            public string Username { get; set; }
            public bool SelectedUsers { get; set; }
            public string AssignToAdmin { get; set; }
        }
        public class AssignRolesModel
        {
            public List<AdminModel> lstAdmins { get; set; }
            [Required(ErrorMessage = "Choose Admin")]
            public string UserId { get; set; }
            public List<UserModel> lstUsers { get; set; }
            public int? AssignToAdmin { get; set; }
            public int? CreatedBy { get; set; }
        }
    


    moving

    Saturday, April 13, 2019 8:47 PM

All replies

  • User283571144 posted

    Hi ExceedingLife,

    According to your view codes, I don't see any codes which is related with the add role button.

    Could you please post more details about add role button codes?

    It will be more easily for us to reproduce the issue and find out the solution.

    Best Regards,

    Brando

    Monday, April 15, 2019 8:00 AM