如何在一个表单中传递多个对象?因为那不工作......请帮帮我
<form class="form-control" action="#" th:action="@{'/'}" method="post">
<select>
<option th:each="city :${cities}" th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
<select>
<option th:each="category :${categories}" th:value="${category.getId()}" th:text="${category.getDescirption()}">
</option>
</select>
//this line isnt correct:
<a class="btn btn btn-primary btn-sm" href="#"
th:href="@{'/todo/done?id=' + ${city.id} + '&name=' + ${category.name}}">done</a>
</form>
答案 0 :(得分:0)
将每个对象添加为命名模型属性。实施例
@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("cities", citiesRepository.getAll());
model.addAttribute("categories", citiesRepository.getAll());
return "message/list";
}
我个人认为将单个对象作为模型属性更具可读性。该对象具有每个实际属性的字段。
有关详细信息,请参阅官方文档https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
在您的示例中,您没有正确使用th:each
。
您应该th:each
为select
级别(不是option
级别),然后引用嵌套select
元素中的各个项目。
像
<select th:each="city :${cities}">
<option th:value="${city.getId()}" th:text="${city.getName()}"/>
</select>
在上一个示例中,您引用的是$ {city.id}和$ {category.name},但未定义城市和类别(可能是thymleaf错误消息告诉您)。
你想要实现什么目标?要与选定的城市和类别建立链接吗?如果是这样,您需要单独的模型属性,如 selectedCity和selectedCatetory。