Send dropdown value to backend using Angular and .Net Core

151 views Asked by At

My backend class looks like this :

public partial class Book
{
    public Book()
    {
        BookAuthors = new HashSet<BookAuthor>();
    }

    public int BookId { get; set; }
    public string Title { get; set; }

    public ICollection<BookAuthor> BookAuthors { get; set; }
}

Between Books and Authors I have a many to many relationship, so BookAuthor is a join table. I am trying to send the data from angular to asp.net core, and in the create book page I have a dropdown with all the authors. My problem is that I cannot send the author picked in the dropdown, what I would like to accomplish would be to insert data in BookAuthor table as well when I create a book, but I cannot have the authorId.

In angular I have this :

 ngOnInit(): void {

this.operation = this.route.snapshot.params['operation'];

this.authorService.getAuthors()
  .subscribe((authors: IAuthor[]) => {
    this.authors = authors,
      authors.forEach((author) => {
        this.authorsDropdown.options.push({ key: author.authorId, value: author.authorName });
      });
  });

if (this.operation === 'create') {
  this.book = {
    bookId: 0, title: '', authors: [], authorsDropdown: this.authorsDropdown 
  };
  console.log(this.book);
} else {
  this.bookService.getBook(this.route.snapshot.params['id'])
    .subscribe((book: Book) => { this.book = book });
}
}

I can see my selected option in the authorsDropdown, but how can I send the authorId to the backend ? In the createBook in Angular I have this:

createBook(book: Book) {
book.bookId = 0;
for (let a of book.authors) {
  a.authorId = Number(this.authorsDropdown.key);
  book.authors.push(a);
} 
this.errorMessage = null;
this.bookService.createBook(book).subscribe(
  b => this.router.navigate(['/authenticated/book-maint']),
  err => this.errorMessage = 'Error creating book'
);

}

And in C# :

public Book Create([FromBody] Book book)
{
  // validation
  if (book == null)
  {
    throw new AppException("Book not found");
  }

  _context.Book.Add(book);
  _context.SaveChanges();

  var bookAuthor = new BookAuthor();
  bookAuthor.BookId = book.BookId;
  bookAuthor.AuthorId = ??

  return book;
}

I hope I managed to explain what I want to do. Thanks !

0

There are 0 answers