-1

I want to create and return an object in this return call:

var Zones = _ZoneService.GetZones();
var userZones = _ZoneService.GetUserZones(user);
return Ok(//Here I need to return both Zones and userZones);

How can I create new on the go object to return these two. Thanks...

Dzianis Yafimau
  • 2,034
  • 1
  • 27
  • 38
  • 2
    Does `return OK(new { Zones, userZones});` work? – mjwills Sep 25 '18 at 10:03
  • 2
    What is `Ok`? A method? Your question is hard to answer unless you provide the signature of the containing method and what `Ok` is. – MakePeaceGreatAgain Sep 25 '18 at 10:05
  • 1
    @HimBromBeere Ok is function from `asp.net core` controller base. – bot_insane Sep 25 '18 at 10:08
  • 1
    Thanks all. This **return OK(new { Zones, userZones});** worked for me. @HimBromBeere Ok is the response in case of WebApi in .net core – Sajad Ahanger Sep 25 '18 at 10:09
  • Possible duplicate of [Return Multiple Objects Using ASP.NET MVC'S JsonResult Class](https://stackoverflow.com/questions/2765082/return-multiple-objects-using-asp-net-mvcs-jsonresult-class) – poke Sep 25 '18 at 10:26
  • Possible duplicate of [Return Multiple Objects Using ASP.NET MVC'S JsonResult Class](https://stackoverflow.com/questions/2765082/return-multiple-objects-using-asp-net-mvcs-jsonresult-class) – Paul Roub Sep 25 '18 at 14:55
  • Related: [How can I return multiple values from a function in C#?](https://stackoverflow.com/questions/748062/how-can-i-return-multiple-values-from-a-function-in-c/748073), [ASP.NET Returning Multiple Variables to View](https://stackoverflow.com/questions/43791585/asp-net-returning-multiple-variables-to-view) – poke Sep 25 '18 at 18:48
  • @ S.Akbari have done that. – Sajad Ahanger Sep 26 '18 at 12:03

3 Answers3

6

What about Anonymous Types? Something like this:

return Ok(new { Zones, userZones });
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

I think that the best way to go is to creat a list, add the object to your list, and return the list. This way is also easyer if you need to work with these object.

To create a list, first we need to code a propper class:

public class Item {
    public int Id { get; set; }
    public Object MyObj { get; set; }
}

Now we can create and populate the list:

List<Item> items = new List<Item>()
{
    new Item{ Id=1, MyObj= Zones},
    new Item{ Id=2, MyObj= userZones}
}

Now you can return your list using: return items

Simo
  • 955
  • 8
  • 18
-2

You could also use anout parameter, like:

public Zones GetZones(..., out Zones userZones)
{
    uzerZones = _ZoneService.GetUserZones(user);
    return _ZoneService.GetZones();
}
Lorena Sfăt
  • 215
  • 2
  • 7
  • 18