33@using BookManagementApp .Services
44@inject NavigationManager Navigation
55@inject BookService bookService
6+ @inject AuthorService authorService
67
78<h3 >Book management</h3 >
89<p >Add details for a new book</p >
2021 <label for =" pages" >Pages</label >
2122 <input type =" number" id =" pages" @bind =" @book.Pages" placeholder =" Number of pages" class =" form-control" />
2223 </div >
24+ <div class =" form-group" >
25+ <label for =" pages" >Author</label >
26+ </div >
27+ <div class =" input-group" >
28+ <select id =" author" @bind =" @AuthorId" class =" form-control" >
29+ @foreach ( var item in authors )
30+ {
31+ <option value =" @item.id" >@item.first_name @item.last_name </option >
32+ }
33+ </select >
34+ <button @onclick =" AddAuthor" type =" button" class =" btn btn-success" >Add Author</button >
35+ </div >
36+ <br >
37+ <legend >Authors</legend >
38+
39+ <div class =" form-group" >
40+ <table class =" table table-striped" >
41+ <thead >
42+ <tr >
43+ <th >Author</th >
44+ <th >Action</th >
45+ </tr >
46+ </thead >
47+ <tbody >
48+ @foreach ( var item in lstAuthors )
49+ {
50+ <tr >
51+ <td >@item.first_name @item.last_name </td >
52+ <td >
53+ <button @onclick =" () => DeleteAuthor(item.id)" type =" button" class =" btn btn-danger" >Delete Author </button >
54+ </td >
55+ </tr >
56+ }
57+ </tbody >
58+ </table >
59+
60+ </div >
2361</form >
2462
2563<div >
2664 <br >
2765 <button @onclick =" AddNewBook" class =" btn btn-success" >Save</button >
66+ <a @onclick =" GoToBooks" class =" btn btn-primary" >Back to books</a >
2867</div >
2968
3069@code {
3170 private Book book = new Book ();
71+ private string ? AuthorId = " " ;
72+
73+ private List <Author > authors = new List <Author >();
74+
75+ private List <Author > lstAuthors = new List <Author >();
76+
77+ protected async override Task OnInitializedAsync ()
78+ {
79+ authors = await authorService .GetAuthors ();
80+
81+ if (authors != null )
82+ AuthorId = " " + authors .FirstOrDefault ().id ;
83+ }
3284
3385 private async Task AddNewBook ()
3486 {
35- await bookService .AddBookAsync (book );
87+ var newBook = await bookService .AddBookAsync (book );
88+
89+ foreach (var itm in lstAuthors ){
90+ await bookService .AddAuthorBookAsync (newBook .Value .FirstOrDefault ().Id , itm .id );
91+ }
92+
3693 // Optionally, you can navigate to a different page after adding the book
3794 Navigation .NavigateTo (" /books" );
3895 }
96+
97+ private async Task AddAuthor ()
98+ {
99+ var authId = int .Parse (" " + AuthorId );
100+ var itm = authors .Where (x => x .id == authId ).FirstOrDefault ();
101+
102+ if (! lstAuthors .Contains (itm )){
103+ lstAuthors .Add (itm );
104+ }
105+ }
106+
107+ private void DeleteAuthor (int ? id )
108+ {
109+ var itm = authors .Where (x => x .id == id ).FirstOrDefault ();
110+ lstAuthors .Remove (itm );
111+ }
112+
113+ protected void GoToBooks ()
114+ {
115+ Navigation .NavigateTo (" /books" );
116+ }
39117}
0 commit comments