Dmitry Dmitry - 17 days ago 6
ASP.NET (C#) Question

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

Answer

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.

Comments