【问题标题】:How to fill a list as object field on client side?如何在客户端填写列表作为对象字段?
【发布时间】:2020-11-12 19:13:54
【问题描述】:

我有实体bookauthor,它们之间是多对多的关系(一本书可以有很多作者,一个作者可以有很多书)。 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


【解决方案1】:

解决方案很简单:我只需将multiple 属性添加到select 标记。绑定系统将在Book 类中找到authors 字段并将List 链接到选定的值。

<form id="bookCreationForm" th:action="@{/books/create}" th:object="${bookModel}"
    method="post">
    <table class="table">
        <!-- some book fields-->
        <tr>
            <td><label th:text="Authors" /></td>
            <td>
                <select class="form-control" name="authors" multiple>
                    <option th:each="author : ${allAuthors}" th:value="${author.id}" th:text="${author}"></option>
                </select>
            </td>
        </tr>
    </table>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-06-19
    相关资源
    最近更新 更多