我有以下型号 -
public class RoleModel
{
public int Id { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public DateTime DateCreated { get; set; }
public int CreatedBy { get; set; }
public DateTime LastUpdated { get; set; }
public int LastUpdateBy { get; set; }
[NotMapped]
public State State { get; set; }
public virtual IEnumerable<UserModel> Users { get; set; }
public virtual IEnumerable<UserModel> UsersNotInRole { get; set; }
public virtual int[] SelectedUsers { get; set; }
public virtual List<RightModel> Rights { get; set; }
public virtual List<RightModel> SelectedRights { get; set; }
public RoleModel()
{
}
}
public class RightModel
{
public string RightName { get; set; }
public string Description { get; set; }
public bool Assigned { get; set; }
}
由此,每个角色都分配了一组权限。从以下视图中,我希望允许用户针对要分配给所选角色的每个权限选中一个复选框。视图正在正确加载数据并检查正确的框,但是当我按“保存”时,权限列表为空。任何想法我如何纠正这一点,以便从所选角色中删除所有权利,然后重新分配所需的权利。
@model Project.Core.Models.Roles.RoleModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="tab-pane" id="tab_1_3">
<table class="table table-striped">
<thead>
<tr>
<th>Right Name</th>
<th>Description</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var right in Model.Rights)
{
<tr>
<td>@Html.DisplayFor(model => right.RightName)</td>
<td>@Html.DisplayFor(model => right.Description)</td>
<td>
<div class="success-toggle-button">
@Html.CheckBoxFor(model => right.Assigned, new { @class = "toggle" })
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
和我的控制器 -
[Authorize]
public ActionResult Details(int id = 0)
{
RoleModel role = _roleService.GetById(id);
if (role == null)
{
return HttpNotFound();
}
return View(role);
}
[HttpPost]
public ActionResult Details(RoleModel model)
{
if (ModelState.IsValid)
{
_roleService.Update(model);
return RedirectToAction("Index");
}
return View(model);
}
和RoleService中的Update方法 -
public void Update(RoleModel entity)
{
entity.LastUpdated = DateTime.Now;
entity.LastUpdateBy = 1;
Role r = _roleRepository.FindById(entity.Id);
AutoMapper.Mapper.CreateMap<RoleModel, Role>();
_roleRepository.Update(AutoMapper.Mapper.Map(entity, r));
}
和我的存储库更新方法 -
public void Update(Role role)
{
_context.ObjectStateManager.ChangeObjectState(role, EntityState.Modified);
SaveChanges();
}
答案 0 :(得分:1)
正如user3153169在评论中所述,对于集合,您需要将您的元素的id / name设置为RoleModel.Rights [i]。为自动播放器找到元素。
所以你应该使用for循环
@for (int i = 0 ; i < Model.Rights.Count() ; i++)
{
<tr>
<td>@Html.DisplayFor(model => Model.Rights[i].RightName)</td>
<td>@Html.DisplayFor(model => Model.Rights[i].Description)</td>
<td>
<div class="success-toggle-button">
@Html.CheckBoxFor(model => Model.Rights[i].Assigned, new { @class = "toggle" })
</div>
</td>
</tr>
}