我正在為我的應用程序做一些前端表單,它將管理家庭收入和結果(家庭預算)。要添加特定的income,用戶必須選擇incomeCategory例如:工資/銷售/禮物等。在以HTML格式準備收入表格時,我想打印incomeCategory為下拉列表,以讓用戶選擇可用的選項之一。該列表是從后端服務接收的,它是 arrayList。我面臨的問題是打印incomeCategory下拉列表中對象的描述值。我發現的每個教程都是硬編碼的,例如:<select name="carlist" form="carform"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option></select>我試圖做的是:<div><label for="incomeCategory" >Category:</label> <select name="incomeCategory" form="incomeCategory"> <tr th:each="temp :${incomeCategories}"> <option value="${temp}" >${temp.description}</option> </tr> </select> <input type="hidden" id="incomeCategory"/></div>我想做一些你在第四行看到的事情。IncomeCategory 類有兩個屬性:public class IncomeCategory{ private Long id; private String description;// constructor, getters, setters}此時,類別循環工作正常,而我的列表中有 3 個項目:是否有可能使用 HTML 和 Thymeleaf 在 dropdownList 中打印類別描述?預先感謝您的幫助。
1 回答

一只甜甜圈
TA貢獻1836條經驗 獲得超5個贊
在您的代碼中,您沒有設置th:text
屬性,并且 thymeleaf 將標記中的文本<option>
(即 ${temp.description})呈現為文本。您應該使用th:text
thymeleaf 屬性來讓 thymeleaf 知道它是一個動態值。另外,th:value
您已經設置了對象引用(temp),您應該使用 temp.id 代替。
假設您已經將 IncomeCategories 列表作為模型屬性傳遞到控制器中,請將選項標簽更改為以下內容
<option value="Sample" th:each="temp :${incomeCategories}" th:value="${temp.id}" th:text="${temp.description}">Sample Description</option>
使用 Thymeleaf,您可以在標簽內循環。我添加了示例和示例描述文本,這樣您只需在瀏覽器中加載 HTML 頁面即可呈現下拉列表,而無需通過 servlet 容器。
添加回答
舉報
0/150
提交
取消