【发布时间】:2016-05-03 14:45:57
【问题描述】:
我在 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);
}
所以当我在 Save 上重新获得帖子时,UserRoles 列表为空,所以我认为我只是在这里遗漏了一个明显的东西?
另一个小问题是 EF Linq 语句。如果我删除
userRole = ur,
来自 Linq 查询的 Select 部分的语句,系统很合适,并说我的架构已过时(事实并非如此)。我认为这是由于以下语句我正在测试外部连接值
HasRole = (ur != null)
虽然这看起来完全合理,并且如果在测试 null(或不)之前使用 ur 变量就可以工作
【问题讨论】:
-
您不能使用
foreach循环为集合生成表单控件(如果您检查 html,您将看到您的输入都具有与您无关的相同name属性模型)。使用for循环或EditorTemplateforUserRoleItem使用索引器生成正确的name属性。有关使用for循环的示例,请参阅 this answer -
谢谢斯蒂芬。在我输入问题后,我实际上将代码更改为使用 EditorTemplates,然后正确生成了数据数组。也许我应该为后代上传解决方案?
-
添加您自己的答案并接受它以关闭它:)
标签: entity-framework model-view-controller asp.net-core checkboxlist