介绍:
最近使用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}"**可以进行两次取值!
到此问题完美解决