我想知道如何创建使用的表单th:object
对于循环中的每个对象th:each
。例如,我有以下代码。
HTML
<th:block th:each="store: ${stores}">
<form th:object="${store}" th:action="@{/modify-store}">
<input th:field="*{idStorePk}"/>
<input th:field="*{name}"/>
<input th:field="*{phoneNumber}"/>
<button type="submit">Modify</button>
</form>
</th:block>
控制器
@RequestMapping(value = "/stores")
public String getIndex(Model model) {
model.addAttribute("stores", storeService.getAllStores());
return "store";
}
因此,我想为每个对象添加一个表单,但似乎不可能,并且出现以下错误。
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'store' available as request attribute
所以,我决定添加一个@ModelAttribute
在我的控制器中,但无法返回实际的商店。
@ModelAttribute("store")
public Store getStore(Store store) {
return store;
}
通过这种方法,我的所有表单都有空值。我还尝试添加一个@PathVariable
,但看不到使用绑定它th:object
。有解决办法吗?
所以对于遇到类似问题的人来说。我找到了一个可能对您有所帮助的解决方法。首先,你不能使用th:object
,它根本不会削减它。相反,请执行以下操作。
<th:block th:each="store: ${stores}">
<form class="store-form" th:action="@{/modify-store}">
<input th:name="idStorePk" th:value="${store.idStorePk}"/>
<input th:name="name" th:value="${store.name}"/>
<input th:name="phoneNumber" th:value="${store.phoneNumber}"/>
<button class="submit-button" type="submit">Modify</button>
</form>
</th:block>
然后添加类似控制器的东西就可以了。
@PostMapping(value = "/modify-store")
@ResponseBody
public boolean deleteEntry(@ModelAttribute Store store) throws Exception {
// Your code here...
return true;
}
如果你想异步发送,那么你需要添加一些JS
代码以使其工作。它应该类似于下面的代码。
const forms = document.querySelectorAll('.store-form');
forms.forEach(form => {
form.addEventListener('submit', event => {
// Stop the normal form submit triggered by the submit button
event.preventDefault();
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)