【发布时间】:2011-12-16 22:04:08
【问题描述】:
我正在尝试创建一个管理部分来管理在 vs 2010 中使用 .net MVC3 的用户。我已经弄清楚了如何分别创建和编辑新用户和角色。但是当我创建或编辑新用户时,我正在努力弄清楚如何添加角色。这是据我所知:
在我的模型中:
public class UserModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class IndexViewModel
{
public IEnumerable<UserModel> Users { get; set; }
public IEnumerable<string> Roles { get; set; }
}
在我的控制器中
public ActionResult Index()
{
return View(
new IndexViewModel
{
Users = Membership.GetAllUsers().Cast<MembershipUser>().Select(x => new UserModel
{
UserName = x.UserName,
Email = x.Email,
}),
Roles = Roles.GetAllRoles()
});
}
在视图中:
@model IEnumerable<BBmvc.Areas.Tools.Models.IndexViewModel>
//...
@foreach (var item in Model) {
foreach (var user in item.Users)
{
<tr>
<td>
@Html.DisplayFor(modelItem => user.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => user.Email)
</td>
<td>
@Html.DisplayFor(modelItem => user.Password)
</td>
<td>
@Html.DisplayFor(modelItem => user.ConfirmPassword)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=user.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=user.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=user.PrimaryKey */ })
</td>
</tr>
}
}
我看到这个错误:
传入字典的模型项是类型 'BBmvc.Areas.Tools.Models.IndexViewModel',但是这本字典 需要“System.Collections.Generic.IEnumerable”类型的模型项
我很困惑。我在正确的轨道上吗?现在我只是试图让角色显示在页面上......最终我需要为每个用户过滤它们,以便只列出用户所在的角色。
编辑: 下面的答案解决了我遇到的视图模型问题。为每个用户显示角色的最终解决方案并没有那么复杂。我在 UserModel 中添加了一个列表:
public IEnumerable<string> UserRoles { get; set; }
在Controller中填写:
public ActionResult Index2()
{
var model = Membership.GetAllUsers().Cast<MembershipUser>().Select(x => new UserModel
{
UserName = x.UserName,
Email = x.Email,
UserRoles = Roles.GetRolesForUser(x.UserName)
});
return View(model);
}
然后在视图中显示:
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@foreach (var role in item.UserRoles)
{
@role
}
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
谢谢大家!
【问题讨论】:
-
你认为的“@model”是什么?
-
@model IEnumerable
标签: asp.net-mvc-3