【发布时间】:2020-11-12 19:13:54
【问题描述】:
我有实体book和author,它们之间是多对多的关系(一本书可以有很多作者,一个作者可以有很多书)。 book 类有一个private List <Author> authors; 字段。我将所有作者的列表作为模型属性传递给视图。该视图返回BbookViewModel 的对象,其字段是选定作者ID 的列表。从select(使用百里香)中选择option 时,如何将此ID 添加到列表中?
BookController
@Controller
public class BookController {
@Autowired
private BookRepository repository;
@Autowired
private AuthorRepository authorRepository;
@GetMapping("/books")
private String getAllBooks(Model model)
{
// some code ...
model.addAttribute("bookModel", new models.Book());
model.addAttribute("allAuthors", authorRepository.findAll());
return "books.html";
}
@PostMapping(value = "/books/create", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public ValidationResponse create(@Valid @ModelAttribute models.Book book, BindingResult result)
{
// ...
}
}
books.html的一部分
<form id="bookCreationForm" th:action="@{/books/create}" th:object="${bookModel}"
method="post">
<table class="table">
<tr>
<td><label th:text="Name" /></td>
<td><input type="text" th:field="*{name}" /></td>
</tr>
<tr>
<td><label th:text="Author" /></td>
<td>
<select class="form-control" /*th:field="${}"*/>
<option value="0">Select author</option>
<option th:each="author : ${allAuthors}" th:value="${author.id}" th:text="${author}"></option>
</select>
</td>
</tr>
</table>
</form>
我应该使用多选并与图书模型分开发送 id 列表吗?
【问题讨论】:
-
看看 HTML 模板和控制器代码会很有帮助。
-
@SlavaIvanov 已更新。
标签: java spring spring-boot thymeleaf