简体   繁体   中英

How can I get field from second table via first table with foreign key from javascript?

I have two simple models: Book:

 public class Book
    {
        public int BookID { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string Year { get; set; }
        public string Publisher { get; set; }

        public int GenreId { get; set; }
        [ForeignKey("GenreId")]
        public Genre Genre { get; set; }
    }

and Genre

public class Genre
    {
        public Genre()
        {
            Books = new List<Book>();
        }
        public int GenreID { get; set; }
        public string Name { get; set; }

        public ICollection<Book> Books { get; set; }
    }

With method from ApiController I get all data from table Books. How can I get in javascript code Name of genre from table Genres using foreign key GenreId ? I would like to write something like book.Genre.Name, but it does not work in js

You can try below code to serialize the object to return to frontend with json format:

var genre = new Genre();
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(Genre);

Or in other way, you can use Json.NET for do that, this is a powerful json object convert lib.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM