【问题标题】:Thymeleaf + Spring form - How load persisted select box values from controller to view?Thymeleaf + Spring form - 如何从控制器加载持久的选择框值以查看?
【发布时间】:2016-04-11 19:17:59
【问题描述】:

在这个question regarding persisting select box elements 中,我设法通过将选定实体的 id 传递给控制器​​并将其传递给我的业务层和 按照我的意愿坚持下去。

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

<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>

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

<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:text="${ftpConnection.getDescription()}">
        </option>
    </select>
</div>

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

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

【问题讨论】:

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


    【解决方案1】:

    在我看来,您只是忘记了 &lt;select&gt; 元素中的 th:field 属性:

    <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>
    

    【讨论】:

    • 我试过了,但没有运气。但我把它修好了。我正在发布答案以供参考。谢谢!
    【解决方案2】:
    <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>
    

    【讨论】:

    • 如果你对你的答案有一些解释,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-28
    • 2020-03-31
    • 1970-01-01
    • 2014-05-16
    相关资源
    最近更新 更多