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();
    }
7
  • You query is creating a collection of anonymous object (with 2 properties ID and NAME) not an array of string Commented Jun 24, 2016 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. Commented Jun 24, 2016 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<Item> listOfUsers = db.CLIENTs.OrderBy)..).Select(r => new Item { ID = r.CLIENTID, Name = r,CLIENTNAME)}; return listOfUsers; and make the method public IEnumerable<Item> Get() Commented Jun 24, 2016 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). Commented Jun 24, 2016 at 23:29
  • I don't see how a string[] could possibly help you. How are you using this data? Commented Jun 24, 2016 at 23:32

2 Answers 2

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);    
} 
Sign up to request clarification or add additional context in comments.

2 Comments

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<<anonymous type: string NAME>>' to 'string[]' If I change it to var listOfUsers... I get error: Error CS0029 Cannot implicitly convert type 'System.Web.Http.Results.JsonResult<System.Collections.Generic.List<<anonymous type: string NAME>>>' to 'System.Web.Mvc.JsonResult'
How to make Get method here accept fromBody object and make it work via POST request?
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.