Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
352 views
in Technique[技术] by (71.8m points)

asp.net mvc Razor SQL tabel

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


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

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...