thymeleaf中的下拉框(select option)回显选中

介绍:

最近使用thymeleaf模板引擎做二手商城项目,在用户修改自己出售的商品信息的时候需要将数据从数据库中查询出来在前端页面进行数据的回显。在input框中的数据回显都没有问题,但是到select框回显的时候却遇到了一些麻烦。特此记录以便查阅!

尝试一:

使用thymeleaf的switch和case来进行判断,将所有的selected属性都设置为selected,将要选中的值与所有的值来做一个switch、case操作,如果case的值等于switch中的值那么则选中。但是这种方法只能显示一个option,其他的选项不显示。不能够修改分类,所以不适用
代码如下:

<select th:name="tid" th:switch="${commodity.tid}">
		<option th:each="type:${allCommodityType}" th:selected="selected" th:case="${type.id}" th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
</select>

尝试2:

后来尝试将值固定写死在的选择项中,这种方式会造成耦合性太强,所以不适用。
代码如下:

<select th:name="tid">
	<option th:selected="${type.id == 1}"  th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
	<option th:selected="${type.id == 2}"   th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
	<option th:selected="${type.id == 3}"  th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
	<option th:selected="${type.id == 4}"   th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
	<option th:selected="${type.id == 5}"   th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
</select>

正确解决方案:

直接使用th:if来进行判断,使用两次取值,一次取得商品中的商品类型编号pid,一次取得商品类型表中的id来进行比较。
代码如下:

<select th:name="tid">
		<option th:each="type:${allCommodityType}" th:selected="${type.id}==${commodity.tid}"  th:value="${type.id}" th:text="${type.typeName}" th:name="tid"></option>
</select>

**selected=" t y p e . i d = = {type.id}== type.id=={commodity.tid}"**可以进行两次取值!
到此问题完美解决

  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值