Thymeleaf + Spring表单 - 如何加载持久性从控制器中选择框值来查看?

时间:2016-04-11 19:17:59

标签: java spring list drop-down-menu thymeleaf

在这个question regarding persisting select box elements中,我设法通过将选择的实体传递给控制器​​并将其传递给我的业务层,并在选择菜单上保留选定的实体。 坚持我的意图。

第一个列表是枚举。这很好用,编辑实体时会加载选定的值。

15.200

问题在于列表对象定义为:

<div class="form-group">
    <label th:for="databaseType">SQL Database Type:</label>
        <select class="form-control" th:field="*{{databaseType}}">
            <option th:each="databaseType : ${T(b.c.m.h.m.SqlDatabaseType).values()}"
                    th:value="${{databaseType}}"
                    th:selected="${databaseType == T(b.c.m.h.m.SqlDatabaseType)}"
                    th:text="${databaseType.databaseType}">
            </option>
        </select>
</div>

现在这个问题恰恰相反。当我单击实体的编辑链接时,选择框被设置为选择框的默认实体值,并且在提交时,默认实体的id被传递到控制器并且它被持久化。

如何确保列表中的选定值是从持久化实体正确加载的值?

2 个答案:

答案 0 :(得分:1)

在我看来,您只是忘记了th:field元素中的<select>属性:

<div class="form-group">
<label th:for="ftpConnection">FTP Connection:</label>
<select class="form-control" name="ftpId" th:field="*{yourFieldName}" >
    <option th:each="ftpConnection : ${ftpList}"
            th:value="${ftpConnection.getId()}"
            th:text="${ftpConnection.getDescription()}">
    </option>
</select>

答案 1 :(得分:0)

<div class="form-group">
    <label th:for="ftpConnection">FTP Connection:</label>
    <select class="form-control" name="ftpId" >
        <option th:each="ftpConnection : ${ftpList}"
            th:value="${ftpConnection.getId()}"
            th:selected="${ftpList.contains(ftpConnection)}"                                
            th:text="${ftpConnection.getDescription()}">
        </option>
    </select>
</div>