我在一个下拉框中有一个管理员列表,在一个面板上有一个用户列表,其中包含他们的名字和一个复选框。我的面板上有一个按钮,因此可以将用户分配给管理员。我想知道如何在控制器中为用户分配角色并不困难,但是这样做并不能100%地确定。这就是我所拥有的。
//我的观点
<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" />
@Html.ActionLink("Cancel", "Dashboard", "SuperAdmin",
null, new { @class = "btn btn-danger" })
</div>
</div>
</div>
</div> //Model public class AdminModel
{
public string UserId { get; set; }
public string Name { get; set; }
}
public class UserModel
{
public string UserId { get; set; }
public string Name { 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; }
} // Controller have a [httppost] and bring my assignrolesmodel object into the controller
获取我拥有的用户列表,但我需要选中用户复选框并将其分配给管理员
答案 0 :(得分:0)
这是我目前想出的。它尚未100%完成,但是我可以找到一个用户并将其分配给管理员,以确保可以与1个用户一起使用,我必须测试多个用户。 我会对所做的任何输入或评论感兴趣。 谢谢
[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.AddToRole(au.Id, "Admin");
}
TempData["Success"] = "Roles Assigned Successfully";
return RedirectToAction("AssignAdmin");
}
}
catch (Exception)
{
throw;
}
return View();
}