0

目标:创建一个可重复使用的下拉菜单,列出我网站的管理员、经理和代理。这些类型的用户由 .NET Simplemembership pages_Roles 和 pages_UsersInRoles 表定义。

到目前为止:我的数据库中有一个 UserProfile 表,它有 25 列。我有一个相应的同名域模型,可以从我的 UsersContext() EF 访问。

下拉菜单只需要列出用户的 FirstName、LastName 和 UserId,因此我没有使用完整的域模型,而是创建了以下 ViewModel:

namespace MyModels.Models.ViewModels
{
    public class AdminsAndAgentsListVM
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int UserId { get; set; }
    }
}

然后我将以下内容添加到我的帐户控制器中(注意我还没有使用部分视图):

public ActionResult AdminsAndAgentsList()
{
   UsersContext _db = new UsersContext(); //provides me access to UserProfiles data
   var admins = Roles.GetUsersInRole("Admin"); //gets users with this role

   var viewModel = _db.UserProfiles
       .Where(x => admins.Contains(x.UserName)); //Selects users who match UserName list
    return View(viewModel);
}

然后,我搭建一个列表视图并将其基于强类型 ViewModel:

    @model IEnumerable<MyModels.Models.ViewModels.AdminsAndAgentsListVM>

@{
    ViewBag.Title = "AdminsAndAgentsList";
}

<h2>AdminsAndAgentsList</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.UserId)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.UserId)
        </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>
}

</table>

我做了一个成功的构建,当我运行网页时,我收到以下错误:

传入字典的模型项的类型为“System.Data.Entity.Infrastructure.DbQuery 1[My.Models.UserProfile]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[My.Models.ViewModels.AdminsAndAgentsListVM]”。

如果我重新创建视图但在 UserProfile 中强烈键入它,它工作正常。那么如何重新工作,以便我可以对我的 ViewModel 进行强类型输入呢?如果可能,请提供示例。我是 C# 和 MVC 的新手,亲眼目睹代码确实让我受益匪浅。非常感谢帮助!

编辑 ------------------ 这是 UserProfile 的对象:

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")

    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    [Required]
    [ReadOnly(true)]
    [DisplayName("SubscriberID")]
    public int? SubscriberId { get; set; } //Foreign key

    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(50, ErrorMessage = "The {0} must be at least {2} characters long.")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    //public DateTime DOB { get; set; }
    [DataType(DataType.Date)]
    public DateTime? DOB { get; set; } //This allows null

    public bool? Gender { get; set; }

    [Required]
    [MaxLength(250)]
    [EmailAddress]
    public string Email { get; set; }

    [MaxLength(250)]
    [EmailAddress]
    [NotEqualTo("Email", ErrorMessage = "Alt Email and Email cannot be the same.")]
    public string AltEmail { get; set; }

    [MaxLength(250)]
    [EmailAddress]
    public string FormEmail { get; set; }

    public Address Address { get; set; }

    [MaxLength(20)]
    public string Telephone { get; set; }

    [MaxLength(20)]
    public string Mobile { get; set; }

    [Required]
    [DataType(DataType.Date)]
    public DateTime DateAdded { get; set; }

    [DataType(DataType.DateTime)]
    public DateTime? LastLoginDate { get; set; }

    public bool? OffersOptIn { get; set; } //any offers we may have with us or partners

    public bool? NewsOptIn { get; set; } //newsletter

    public bool? SubscriptionOptIn { get; set; } //account, technical, renewal notices, pp invoices, pp receipts

    public bool? OrderOptIn { get; set; } //orders - workflow notices

    [DataType(DataType.DateTime)]
    public DateTime? LastUpdatedAccountDate { get; set; } //Last time user updated contact info
}
4

4 回答 4

2

试试这个。它会将您的查询投射到您的视图模型中。

var viewModel = _db.UserProfiles
       .Where(x => admins.Contains(x.UserName))
       .Select(x => new AdminsAndAgentsListVM { 
                        FirstName = x.FirstName,
                        LastName = x.LastName,
                        UserId = x.UserId});
于 2012-10-11T22:09:37.670 回答
1

您传递的是您的查询视图,而不是您的模型。

按您的方式执行查询

var query = _db.UserProfiles
           .Where(x => admins.Contains(x.UserName));

然后实例化并填充您的视图模型

var viewModels = new List<AdminsAndAgentsListVM>();
foreach (var item in query)
{
var viewModel = new AdminsAndAgentsListVM();
     viewodel.FirstName = item.FirstName;
     viewodel.LastName = item.LastName;
     viewodel.UserId = item.UserId;
viewModels.Add(viewModel);
}



  return View(viewModels);

当然,这假设 UserProfile 和 AdminsAndAgentsListVM 具有匹配的属性。

于 2012-10-11T20:18:10.383 回答
0

将您的退货行更改为:

return View(viewModel.AsEnumerable());

于 2012-10-11T20:11:13.187 回答
0

您没有选择 ViewModel。您需要在查询中执行 Select(x => new AdminsAndAgentsListVM。我也会在那里执行 ToList()。

于 2012-10-11T20:11:38.040 回答