如何在视图中从控制器打印linq查询的结果?

时间:2016-03-04 15:48:19

标签: c# linq asp.net-mvc-4

我在控制器中有以下代码

  public ActionResult Linq()
        {
            List<region> Regiones = db.region.ToList();
            List<comuna> Comunas = db.comuna.ToList();

            var  resultado = from r in Regiones
                            join c in Comunas on r.r_id equals c.c_region
                            where r.r_id == 8
                            select new
                            {
                                region = r.r_region,
                                comuna = c.c_comuna
                            };
            ViewBag.resultado = resultado;
            return View();
        }

并在视图中

 @{ 
                           foreach(var a in ViewBag.resultado)
                           {
                              <tr><td>
                                  @a.comuna
                              </td></tr> 
                           }
                       }

但是当这次运行时,我有以下错误:

  

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'object'no contieneunadefiniciónpara'comuna'。

发生什么事了?我如何在视图中打印所有“comuna”?

谢谢!

1 个答案:

答案 0 :(得分:3)

可能的解决方案之一是为结果创建一个新类型,如

public class Address //some good name
{
    public int Region  {get;set;};
    public string Comuna {get;set;} ;
}

他们修改你的行动

public ActionResult Linq()
{
    List<region> Regiones = db.region.ToList();
    List<comuna> Comunas = db.comuna.ToList();

    var  resultado = from r in Regiones
                    join c in Comunas on r.r_id equals c.c_region
                    where r.r_id == 8
                    select new Address
                    {
                        Region = r.r_region,
                        Comuna = c.c_comuna
                    };
    return View(resultado);
}

并更改视图:

 @model System.Collections.Generic.IEnumerable<Address>

 @{ 
   foreach(var a in Model)
   {
      <tr><td>
          @a.Comuna
      </td></tr> 
   }
}