请写出 thymeleaf获取后端列表数据回显在下拉框中
时间: 2023-04-11 07:00:55 浏览: 140
可以使用th:each遍历后端传递的列表数据,将每个数据项添加到下拉框中,使用th:selected属性判断哪个选项应该被选中,示例代码如下:
<select>
<option th:each="item : ${list}"
th:value="${item.id}"
th:text="${item.name}"
th:selected="${item.id == selectedId}"></option>
</select>
其中,${list}是后端传递的列表数据,${item.id}和${item.name}分别是列表项的id和name属性,${selectedId}是前端传递的选中项的id。
相关问题
请写出 thymeleaf获取后端Integer列表数据回显在下拉框中
可以使用th:each遍历Integer列表,将每个元素作为下拉框的选项,使用th:selected属性判断哪个选项被选中,示例代码如下:
<select>
<option th:each="num : ${integerList}"
th:value="${num}"
th:text="${num}"
th:selected="${num == selectedNum}">
</option>
</select>
其中,integerList是后端传来的Integer列表,selectedNum是当前选中的数字。
thymeleaf 复选框回显_thymeleaf下拉框从后台动态回显选中
Thymeleaf可以通过th:checked属性来控制复选框是否选中,动态回显选中的复选框可以通过在后台设置该属性来实现。以下是一个示例:
```
<form th:object="${user}" method="post">
<div>
<label>爱好:</label>
<input type="checkbox" name="hobbies" value="reading" th:checked="${user.hobbies.contains('reading')}"/> 阅读
<input type="checkbox" name="hobbies" value="writing" th:checked="${user.hobbies.contains('writing')}"/> 写作
<input type="checkbox" name="hobbies" value="traveling" th:checked="${user.hobbies.contains('traveling')}"/> 旅游
</div>
<button type="submit">保存</button>
</form>
```
在这个例子中,我们假设我们有一个User对象,其中有一个List类型的hobbies属性,用于存储用户的爱好。在表单中,我们为每个可能的爱好创建了一个复选框,并使用th:checked属性来控制哪些复选框应该被选中。
`th:checked="${user.hobbies.contains('reading')}"`这一行代码是关键,它检查用户的兴趣列表是否包含“阅读”这个字符串,并相应地将复选框标记为选中或取消选中。同样,我们对每个其他的兴趣选项进行相同的检查。
在处理表单提交时,用户的兴趣列表将被更新,并且我们可以像使用任何其他表单字段一样处理它。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)