如何在MVC控制器中返回json中的列表linq?

时间:2015-12-25 08:12:44

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

 iconv -f UTF-16 -t UTF-8 originFile > destinationFile

此代码给出了以下错误。

  

无法隐式转换类型&#39; public List<Detail> GetOrderDetails() { var orderDetails = (from user in db.Users join detail in db.OrderDetails on user.Id equals detail.UserId where (detail.DateAdded != null) select new Detail { FirstName = user.FirstName, LastName = user.LastName, Origin = detail.OriginCode, Destination = detail.DestinationCode, CarrierCode = detail.CarrierCode, IsReturn = detail.IsReturn, IsCancel = detail.IsCancel, OrderId = detail.OrderId }).FirstOrDefault(); return Json(orderDetails); } &#39;至   &#39; System.Web.Mvc.JsonResult

2 个答案:

答案 0 :(得分:5)

<强>问题:

  1. (your query).FirstOrDefault();返回的元素不是列表。
  2. Json(x)将x转换为包含x的json表示的字符串。
  3. 以下是您的选择:

    1. 如果要返回对象列表,可以删除FirstOrDefault()并使用return (your query).ToList()
    2. 您可以将方法的返回类型更改为Detail而不是List<Detail>,然后使用return orderDetails;代替return Json(orderDetails);
    3. <强>更新

      根据您想要&#34;在MVC控制器中的json中返回列表&#34;

      的问题标题推断

      您应该将方法更改为此

      public ActionResult GetOrderDetails()
      {
          var orderDetails = (from user in db.Users
                              join detail in db.OrderDetails
                              on user.Id equals detail.UserId
                              where (detail.DateAdded != null)
                              select new Detail
                              {
                                  FirstName = user.FirstName,
                                  LastName = user.LastName,
                                  Origin = detail.OriginCode,
                                  Destination = detail.DestinationCode,
                                  CarrierCode = detail.CarrierCode,
                                  IsReturn = detail.IsReturn,
                                  IsCancel = detail.IsCancel,
                                  OrderId = detail.OrderId
                              }).ToList();
      
          return Json(orderDetails, JsonRequestBehavior.AllowGet);
      }
      

答案 1 :(得分:1)

只需将您的返回类型更改为JsonResult并使用.tolist()方法转换为列表返回Json(orderdetails.tolist(),jsonrequestbehaviour.allowget)如果您通过&发送请求,它将取决于您的请求#34;邮政&#34;方法然后在方法名称的顶部使用[httppost]属性并删除&#34; jsonrequestbehaviour.allowget&#34;从您的代码中,它将适合您。