我想使用 HTML 表单将多个项目从数据库显示到 Thymeleaf View ,以便我可以对数据库进行更改和更新。
我打算使用 th:field 。但发生了错误。当我尝试使用th:value时。并且它显示数据。
<div th:each="item : ${courses}">
<form th:object="${item}">
<input th:field="*{name}" type="text" id="name" name="name" /> // error occur
</form>
</div>
以下错误。
Neither BindingResult nor plain target object for bean name 'item' available as request attribute
而下面的代码工作正常。
<div th:each="item : ${courses}">
<form th:object="${item}">
<input th:value="*{name}" type="text" id="name" name="name" /> // ok
</form>
</div>
我走在正确的道路上吗?你能解释一下为什么吗?字段和值之间的区别?
最佳答案
底线是您只能使用 th:object
和th:field
一起在基本模型属性上。这意味着您在迭代时无法使用它(因为模型中不存在 ${item}
,它是由 th:each
生成的变量)。要求已详细说明here :
Values for
th:object
attributes in form tags must be variable expressions (${...}
) specifying only the name of a model attribute, without property navigation. This means that an expression like${seedStarter}
is valid, but${seedStarter.data}
would not be.Once inside the
<form>
tag, no otherth:object
attribute can be specified. This is consistent with the fact that HTML forms cannot be nested.
th:field
设置name
, id
,和value
一个字段的。因此它们在某种程度上可以互换,但您应该使用 th:field
只要有可能,因为它提供了与 spring 的额外集成,并且适用于所有类型的输入 - 但这些实际上仅在您编辑页面上的单个对象时才有用。
由于您要迭代多个对象,因此您必须手动设置 name
, id
,和value
就像你正在做的那样。
关于java - Spring MVC 和 Thymeleaf - 之间有什么区别 :value and th:field when you iterate multiple items?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677313/