我应该如何从一个Controller Action返回两个对象列表?

时间:2015-02-26 15:03:46

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

我有两个不同的列表来自同一个对象。我希望将这两个作为单独的列表同时获取,或者在返回JSON对象时加入这两个相同的列表。

这是我的代码。

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

return Json(GetUserNames, JsonRequestBehavior.AllowGet);

2 个答案:

答案 0 :(得分:6)

我更愿意这样做:返回的项目是不同的类型。而不是返回带有类型鉴别器的裸JSON列表,而是返回一个多属性JSON对象:

return Json(new 
{ 
    Names = GetUserNames, 
    Profiles = GetProfile 
}, JsonRequestBehavior.AllowGet);

您返回的JSON将{Name, Id}个对象分为其类型,格式为草图:

{ 
  Names: [
   {Name:"UserName", Id:"3"}, 
   {Name:"OtherUser", Id: "4"}
  ],
  Profiles: [
   {Name:"Normal", Id:"1"}, 
   {Name:"Admin", Id: "99"}
  ]
}

在大多数JSON.Net客户端解析方案中(即从WPF智能客户端使用WebAPI),您自动映射(例如来自RestSharp)将允许您将其反序列化为表格类

public class NameId
{
     public int Id {get; set;}
     public string Name {get; set;}
}

public class UserNamesResponse
{
     public List<NameId> Names {get; set;}
     public List<NameId> Profiles {get; set;}
}

这可能比交错列表更方便,更清晰,无论如何必须将其过滤到单独的列表中....(或者在UI绑定层中以性能损失的方式通过过滤类型转换器... )

答案 1 :(得分:2)

您可以使用GetUserNames.Concat(GetProfile)

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new
    {
        Name = u.Name,
        Id = u.Id
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
  new
  {
      Name = u.Name,
      Id = u.Id
  })).ToList();

return Json(GetUserNames.Concat(GetProfile) , JsonRequestBehavior.AllowGet);

Enumerable.Concat Method

根据评论更新

创建一个类和枚举:

public class NameId
{
    public string  Name {get;set;}
    public string  Id {get;set;}
    public ThisType Type { get; set; }
}

public enum ThisType
{
   Username,
   Profile
}

然后返回:

List<User> userEntity = users.Where(s => s.Id == Id).ToList();

var GetUserNames = userEntity.SelectMany(s => s.Names.Select(u =>
    new NameId
    {
        Name = u.Name,
        Id = u.Id,
        Type = ThisType.Username
    })).ToList();

var GetProfile = userEntity.SelectMany(s => s.Profile.Select(u =>
  new NameId
  {
      Name = u.Name,
      Id = u.Id,
      Type = ThisType.Profile
  })).ToList();

return Json(GetUserNames.Concat(GetProfile) , JsonRequestBehavior.AllowGet);