无法转换类型匿名类型?

时间:2013-10-04 02:10:17

标签: json asp.net-mvc-4 razor partial-views anonymous-types

我想将查询结果(JSON)从控制器传递到局部视图,这就是我创建强类型的原因如下:

public class Suivi_Client
{
    public string ClientID { get; set; }
     public string Activite { get; set; }
     public string ClientName { get; set; }
}

// list 
public class Suivis
{
    public List<Suivi_Client> List_Clients { set; get; }
}

然后是局部视图:

 @model IEnumerable<Project.Models.Suivi_Client>
<html>
    <body>
<table border=1>
<thead>
  <tr>
   <th>
    ID
  </th>
   <th>
    Name
  </th>
        <th>
    Activite
  </th>
  </tr>
</thead>
@foreach(var item in Model){
foreach (var pop in item.List_Clients)
{
<tr>
    <td >
        @Html.DisplayFor(modelItem => pop.ClientID)
    </td>
    < <td >
        @Html.DisplayFor(modelItem => pop.ClientName)
    </td>
     <td >
        @Html.DisplayFor(modelItem => pop.Activite)
    </td>

</tr>
}
}
</table>
    </body>
    </html>

这是动作方法:

public ActionResult  Partial_suivi(string clients)
        {
         IEnumerable<Suivis> PopModel;
              var activit = (from x in frh.productivites
                         join y in frh.Clients on x.action equals y.ClientName
                         where x.action.Equals(clients)
                         select new { x.actionID,x.Activité,y.ClientName,y.Responsable,y.TempsCible,x.tempsmoy_ }).Distinct().ToArray();
        PopModel = activit;
            return PartialView(PopModel);
        }

但是我有这个错误:无法将'AnonymousType#1 []'类型转换为'Project.Models.Suivis

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

这里有几个问题。

在您的操作方法中,您尝试将IEnumerable<Suivis>传递给您的视图。

但您的观点期待IEnumerable<Suivi_Client>

接下来的问题是您的linq查询是select(转换)为匿名对象,但您尝试将其放入IEnumerable<Suivis>

我要猜测你想要做的是让你的linq查询选择IEnumerable<Suivi_Client>,以便你的视图可以做到这一点。为此,您可以将代码更改为类似于

的代码
IEnumerable<Suivi_Client> PopModel = (from x in frh.productivites
                                      join y in frh.Clients on x.action equals y.ClientName
                                      where x.Action.Equals(clients)
                                      select new Suivi_Client 
                                         { 
                                             Activite = x.Activite,
                                             ClientName = y.ClientName,
                                             ClientID = ??
                                         }).Distinct();

return PartialView(PopModel);

您提供的代码中存在许多未知数,并且您使用的是未在代码段中显示的对象。如果你能解释你想要你的linq查询实际做什么,我相信有人可以发布一个更完整/更好的例子来说明如何实现你所追求的目标。