Paul X
Paul X

Reputation: 379

Proper way to return JSON list in Web API with MVC and partial model

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();
    }

Upvotes: 1

Views: 17059

Answers (2)

user3559349
user3559349

Reputation:

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)

Upvotes: 2

Legends
Legends

Reputation: 22672

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);    
} 

Upvotes: 3

Related Questions