我试图获取所选复选框的值并将其传递给我的操作,以便我可以更改角色。我有一个模型属性的复选框,并用for循环填充。我有一个Beginform可以解决这个问题,但是我的提交不在forloop中,所以我无法将选中的复选框用于操作。 问题是我曾经使用相同的代码来工作,所以我知道它可以工作。当我的视图上只有1 beginForm()时,就可以使用它。我将选定的复选框用户发送给我的操作,它成功更改了角色。现在,我很难将用户发送到操作上。 这是我的代码
// View
@using (Html.BeginForm("AssignAdmin", "SuperAdmin", FormMethod.Post))
{
@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>
} [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();
} 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; }
}