使用viewdata.model将db查询发送到视图

时间:2014-11-04 09:00:05

标签: c# asp.net-mvc

我想使用viewdata.model将查询结果发送到视图。但该模型需要一个类型为Ienumerable的模型项。

private RScontextSansEDM db = new RScontextSansEDM();
ViewData.Model = (from a in db.TmembresansEDMdb
                  join b in db.dbTassociation on a.Idassociation equals b.Idassociation
                  where a.Idassociation == ListeMembre.Idassociation
                  select new { a });
return View();

执行时出错。

The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[<>f__AnonymousType31[RSTestSansEdm.‌​Models.Tmembre]]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[RSTestSansEdm.Models.Tmembre]'

和模型:

namespace RSTestSansEdm.Models
{
  public partial class Tmembre
  {

    [Key]
    public int Idmembre { get; set; }
    public string Nommembre { get; set; }
    public string Prenommembre { get; set; }
    public string Mailmembre { get; set; }
    public string SRCImage { get; set; }
    public int Idassociation { get; set; }

    //public virtual IEnumerable<Tmembre> MembreAssociation { get; set; }
  }

观点:

@model IEnumerable<RSTestSansEdm.Models.Tmembre>
@foreach (var item in Model) {        
  <div class="divmembre">
    <div class="dphoto"><img src="~/Content/@item.SRCImage"/></div>

请帮助:)

1 个答案:

答案 0 :(得分:0)

这一行

select new { a });

正在创建一个匿名对象。将其更改为

ViewData.Model = (from a in db.TmembresansEDMdb
              join b in db.dbTassociation on a.Idassociation equals b.Idassociation
              where a.Idassociation == ListeMembre.Idassociation
              select a);