开发者

How to convert a list of anonymous object to string array using linq for return using Json Result in ASP.NET MVC

I currently have a list of a book object as f开发者_高级运维ollows:

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?


have you tried:

// this will return a List<string>
var result = books.Select(p => p.Author).ToList(); 
return Json(new { authors = result });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜