views:

16

answers:

1

I currently have a list of a book object as follows:

public class Book()
{
    public int BookId { get; set; }
    public string Name { get; set; }
    public string Author { get; set; }
}

List<Book> books = BookRepository.SelectAll();

I would like to return a string list/array of Authors for return via a Json Result in my action method. At the moment I have done:

var result = books.Select(p => new { p.Author }).ToList();
return Json(new { authors = result });

However, inspecting the result gives the following JSON:

{
    authors: [
        { Author: "John" },
        { Author: "Gary" },
        { Author: "Bill" },
        { Author: "Ray" }
    ]
}

However, I do not want each Author as a seperate object in the JSON. I would like the result as:

{
    authors: ["John", "Gary", "Bill", "Ray"]
}

How do I go about achieving this?

+2  A: 

have you tried:

// this will return a List<string>
var result = books.Select(p => p.Author).ToList(); 
return Json(new { authors = result });
John Boker
Correct. You need a string list named authors, rather than a list of anonymous objects with Author properties.
JoshJordan
Perfect - worked like a charm. Thanks
Astrofaes