使用Angular和.Net Core将下拉值发送到后端

时间:2018-06-24 19:14:02

标签: .net angular entity-framework dropdown

我的后端类如下:

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; }
}

在书籍和作者之间,我有多对多的关系,因此BookAuthor是一个联接表。我正在尝试将数据从angular发送到asp.net核心,在创建书页面中,我与所有作者都有一个下拉列表。我的问题是我无法发送下拉列表中选择的作者,我想完成的工作是在创建书籍时也将数据插入BookAuthor表中,但是我不能拥有authorId。

在角度上我有这个:

 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 });
}
}

我可以在authorsDropdown中看到我选择的选项,但是如何将authorId发送到后端?在Angular的createBook中,我有以下内容:

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'
);

}

在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;
}

我希望我能解释我想做什么。谢谢!

0 个答案:

没有答案