1

I am trying to use Web API to grab certain fields from my MVC controller. I can't seem to match the right type with the right list. I am fine with converting everything to string.

I either get an error in code (can not convert types), or if I get it to compile, I get this error:

"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'."

From other similar posts, people responded with how to create a list, but not with the declaration of the return value of the Get. Please include both.

Also I would prefer not to add additional controllers as I need to do this on a number of my models.

Here is my code--note you can see I tried a number of different ways:

public class APICLIENTsController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET api/<controller>
    public IEnumerable<string> Get()
    //public IEnumerable<CLIENT> Get()
    {
        //return db.CLIENTs.OrderBy(x => x.CLIENTNAME).ToList();
            string[] listOfUsers = db.CLIENTs.OrderBy(x => x.CLIENTNAME).Select(r => new
            {
                ID = r.CLIENTID.ToString(),
                NAME = r.CLIENTNAME
        });

        return listOfUsers.ToList();
        //return db.CLIENTs.Select(x => new { x.CLIENTNAME }).ToArray();
    }
Paul X
  • 379
  • 1
  • 3
  • 10
  • You query is creating a collection of anonymous object (with 2 properties `ID` and `NAME`) not an array of `string` –  Jun 24 '16 at 23:11
  • So how do I fix? I am starting with an iqueryable model and i don't mind converting it to anything that I can pull out of this api. – Paul X Jun 24 '16 at 23:15
  • Not clear what you really want to return. If you want to return a collection of objects, create a view model (say `class Item` with `int ID` and `string Name`) and use `IEnumerable listOfUsers = db.CLIENTs.OrderBy)..).Select(r => new Item { ID = r.CLIENTID, Name = r,CLIENTNAME)}; return listOfUsers;` and make the method `public IEnumerable Get()` –  Jun 24 '16 at 23:22
  • I have a number of these api calls to make so I don't want to create 20 view models. I just want the easiest way to get this out to Json. I am fine with converting everything to string if I could just do it in the function (but I don't know how). – Paul X Jun 24 '16 at 23:29
  • I don't see how a `string[]` could possibly help you. How are you using this data? –  Jun 24 '16 at 23:32
  • @PaulX, look [here](http://stackoverflow.com/q/14962134/2581562) – Legends Jun 25 '16 at 00:02
  • Thanks for all your help. I set up a simple view model, used the select in the third comment above) and removed xml from the output to see it in my browser, and it all worked. If you submit it as an answer, I will accept. – Paul X Jun 26 '16 at 13:58

2 Answers2

3

If you want to return JSON use the

JsonResult

type.

public JsonResult Get()
{
    //return db.CLIENTs.OrderBy(x => x.CLIENTNAME).ToList();
    string[] listOfUsers = db.CLIENTs.OrderBy(x => x.CLIENTNAME).Select(r => new
    {
        ID = r.CLIENTID.ToString(),
        NAME = r.CLIENTNAME
    });

    return Json(listOfUsers.ToList(), JsonRequestBehavior.AllowGet);    
} 
Legends
  • 21,202
  • 16
  • 97
  • 123
  • Thanks. This points me in the right direction, but... If I do string[] listOfUsers.., I get error: Error CS0029 Cannot implicitly convert type 'System.Linq.IQueryable<>' to 'string[]' If I change it to var listOfUsers... I get error: Error CS0029 Cannot implicitly convert type 'System.Web.Http.Results.JsonResult>>' to 'System.Web.Mvc.JsonResult' – Paul X Jun 24 '16 at 22:57
  • How to make Get method here accept fromBody object and make it work via POST request? – Alexander Jun 12 '17 at 17:38
2

Your query is returning a collection of anonymous objects, not string[] so it will throw an exception. Even if you were to generate string[] by concatenating the CLIENTID and CLIENTNAME properties, it would be a little use to the client.

Create a model to represent what you need to return to the view

public class ClientVM
{
    public int ID { get; set; }
    public string Name { get; set; }
}

and modify your method to

public IEnumerable<ClientVM> Get()
{
    IEnumerable<ClientVM> model = db.CLIENTs.OrderBy(x => x.CLIENTNAME).Select(r => new ClientVM
    {
        ID = r.CLIENTID,
        Name = r.CLIENTNAME
    });
    return model;
}

Side note: depending on how your calling and consuming this in the client, you may need to change the Content-Type to specifically return json (refer these answers for more detail)

Community
  • 1
  • 1