You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Thymeleaf中如何将item.id的值赋值给itemID字段?

解决Thymeleaf中把item.id赋值给itemID输入框的问题

嘿,我来帮你搞定这个问题!你之前的写法无效,核心原因是Thymeleaf的th:field会覆盖th:value——因为th:field是双向绑定属性,它会自动生成name、id和value,你手动加的th:value会被直接忽略掉。

下面给你两种可行的解决方案,根据你的场景选:

方案1:后端提前赋值(推荐)

这是最符合Thymeleaf设计思路的方式。在你的Controller里,把item.id的值直接设置到表单对象的itemID字段中:

// 假设你的表单对象是BidForm(替换成你实际的表单类)
BidForm form = new BidForm();
form.setItemID(item.getId()); // 把item.id的值赋值给itemID
model.addAttribute("bidForm", form);

然后前端直接用th:field绑定itemID就行,输入框会自动填充对应的值:

<input type="text" th:field="*{itemID}" placeholder="Bidding id" class="form-control" required />

这种方式不需要额外的隐藏字段,逻辑清晰,也不容易出问题。

方案2:前端直接绑定值(无需后端修改)

如果因为某些原因不能在后端调整,你可以放弃th:field,手动指定name、id和value:

<input type="text" name="itemID" id="itemID" th:value="*{item.id}" placeholder="Bidding id" class="form-control" required />

这样输入框会显示item.id的值,提交表单时,参数itemID会带着这个值传给后端。这种方式是单向绑定,但如果需要修改输入框的值并回传,也能正常工作,因为name属性和后端字段已经对应上了。

另外,你之前的隐藏字段<input type="hidden" th:field="*{item.id}" />如果已经不需要了,可以删掉,避免冗余。

内容的提问来源于stack exchange,提问作者Nguyễn Eric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:07:23