MVC ViewModel错误

时间:2012-10-11 20:08:06

标签: asp.net-mvc-4 asp.net-mvc-viewmodel

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

到目前为止: 我的数据库中有一个包含25列的UserProfile表。我有一个相同的域名模型,可以从我的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.IEnumerable 1 [My.Models.ViewModels.AdminsAndAgentsListVM]'。

如果我重新创建视图但强烈再次键入UserProfile,它可以正常工作。那么如何重新开始工作呢?我可以强烈反对我的ViewModel?如果可能,请提供示例。我是C#和MVC的新手,真正受益于第一手看到代码。非常感谢帮助!

EDIT ----------------------------- 以下是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 个答案:

答案 0 :(得分:2)

试试这个。它会将您的查询转换为您的视图模型。

var viewModel = _db.UserProfiles
       .Where(x => admins.Contains(x.UserName))
       .Select(x => new AdminsAndAgentsListVM { 
                        FirstName = x.FirstName,
                        LastName = x.LastName,
                        UserId = x.UserId});

答案 1 :(得分: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具有匹配的属性。

答案 2 :(得分:0)

将您的回程行更改为:

return View(viewModel.AsEnumerable());

答案 3 :(得分:0)

您没有选择ViewModel。您需要在查询中执行Select(x =&gt;新的AdminsAndAgentsListVM。我也会在那里执行ToList()。