0
我做用户角色MVC6(使用EF7),我想我只是失去了一些东西,但用来定义一个用户角色在表单上我什么也没得到在调回模型控制器获取核对清单数据
这是我的模型
public class UserRoleItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IdentityUserRole<int> userRole { get; set; }
public bool HasRole { get; set; }
}
public class UsersRolesViewModel
{
public int UserId { get; set; }
public string FullName { get; internal set; }
public List<UserRoleItem> UserRoles;
}
这是视图
@model Skill.ViewModels.Manage.UsersRolesViewModel
<br />
<h3>Set Roles for user - @Model.FullName</h3>
<form asp-action="ChangeUsersRoles" >
<div class="form-horizontal">
<hr />
<input type="hidden" asp-for="UserId" />
@foreach (var userRole in Model.UserRoles)
{
<input type="hidden" asp-for="@userRole.Id" />
<div class="form-group">
<div class="inline-block col-md-8">
<span class="col-md-1" align="center">
<input type="checkbox" asp-for="@userRole.HasRole" />
</span>
<div class="col-md-7">
@userRole.Name (@userRole.Description)
</div>
</div>
</div>
}
<hr />
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>
这是控制器
// GET: Users/ChangeUserRoles/5
public async Task<IActionResult> ChangeUserRoles(int? id)
{
if (id == null)
{
return HttpNotFound();
}
var model = new UsersRolesViewModel();
ApplicationUser appUser = await _context.ApplicationUsers.SingleAsync(m => m.Id == id);
if (appUser == null)
{
return HttpNotFound();
}
else
{
model.UserId = (int)id;
model.FullName = appUser.FullName;
var some = from r in _context.Roles
from ur in _context.UserRoles
.Where(inner => r.Id == inner.RoleId && inner.UserId == id)
.DefaultIfEmpty()
select new UserRoleItem
{
Id = (int)r.Id,
Name = r.Name,
Description = r.NormalizedName,
userRole = ur, // this is needed else it has a hissy fit
HasRole = (ur != null)
};
// get all of the Roles and then also link to the ones the user currently has
model.UserRoles = (some).ToList();
}
return View(model);
}
// POST: Users/ChangeUserRoles/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangeUserRoles([Bind(include:"UserId,UserRoles")]UsersRolesViewModel userModel)
{
if (ModelState.IsValid)
{
// update based on the changes
// return RedirectToAction("Edit", new { userModel.UserId });
}
return View(userModel);
}
所以,当我得到这个职位,回到保存,该名单的UserRole为空,所以我想我只是缺少一个显而易见的事情吗?
也是另一个小问题是EF Linq的语句。如果我从Linq查询的Select部分中删除
userRole = ur,
声明,那么系统就会适合并说我的模式已过期(不是)。我认为这是由于下面的语句,我正在测试外连接值
HasRole = (ur != null)
尽管这似乎是完全合理的,如果乌拉圭回合变量之前测试零使用(或不)的作品
您不能使用'foreach'循环来生成表单控件集合(如果你检查HTML,你会看到你输入的所有有需要你的模型没有任何关系一样'name'属性)。使用'for'环或'EditorTemplate'为'UserRoleItem'产生name'与索引属性正确的'。对于使用'for'环的例子,请参见[此答案](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416# 29554416) –
谢谢斯蒂芬。我走进这个问题后,我居然改变了代码使用EditorTemplates,然后正确生成数据的阵列。也许我应该为后代上传解决方案? –
添加你自己的答案,并接受它关闭此:) –