Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm noobie in this, but I'm learning.

This is an database SQL question. This was really easy in classic ASP.

I have 2 tables in my database. Books and genre.

In my show books page, you'll get from db:

| Book name | book Author | book genre |
+-----------+-------------+------------+
| eden      | paulo       | 1          |
| mystic    | paulo       | 2          |

The genre is

| id  | book genre |
+-----+------------+
| 1   | action     |
| 2   | horror     |

What I like is

| Book name | book Author | book genre |
+-----------+-------------+------------+
| eden      | paulo       | action     |
| mystic    | paulo       | horror     |

As I said earlier this was super easy in classic asp.

How can I do this in ASP.NET MVC with Razor?

Best, Andy


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
299 views
Welcome To Ask or Share your Answers For Others

1 Answer

If your Book and Genre table are already connected with the Foreign key then you can fetch the data like this.

Create a view model:

public class BookList{
  public string Name  {get;set;}
public string Author {get;set;}
public string Genre {get;set;}
}

var books  = _context.Books.Include(x=>x.Genre).Select(x=> new BookList(){
  Name = x.BookNmae,
  Auther = x.BookAuthor,
  Genre = x.Genre.BookGenre
}).ToList()

Send this model to a view :

and in view you just need to loop through the model to create table rows.

<table>
<thead> <th>Book Name</th><th>Book Author</th><th>Book Genre</th></thead>
<tbody>
@foreach(var m in Model){
 <tr><td>@m.Name</td><td>@m.Author</td><td>@m.Genre</td></tr>
}
</tbody>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...