简体   繁体   English

使用SpringMVC和Thymeleaf提交时为空表格

[英]Empty form when submitting with SpringMVC and Thymeleaf

I'm trying to edit data (checkboxes) in a table. 我正在尝试编辑表中的数据(复选框)。 But when I click on the submit button, the form in the controller is empty 但是当我单击提交按钮时,控制器中的表单为空

I didn't find a example with thymeleaf so I adapted this example 我没有找到百里香的例子,所以我改了这个例子

I use a form object: 我使用一个表单对象:

public class MyForm {
  private List<MyObj> data;
  // ...
}

The controller with the two methods (GET and POST): 具有两种方法(GET和POST)的控制器:

@RequestMapping(value="/edit/", method = RequestMethod.GET)
public String editGet(Model model) {
  MyForm form = new MyForm(data);
  model.addAttribute("myForm", form);
  return "editPage";
}

@RequestMapping(value="/edit/save", method = RequestMethod.POST)
public String editPost(@ModelAttribute("myForm") MyForm myForm, Model model) {
 // here myForm.getData() is empty
}

And my html: 和我的HTML:

<form th:action="@{/edit/save}" th:object="${myForm}" method="POST">
  <table>
    <thead>....</thead>
      <tbody th:each="myObj : *{data}" th:remove="tag">
        <tr>
          <td><span th:text="${myObj.name}"></span></td>
          <td><input type="checkbox" th:checked="${myObj.isOK}"/></td>
        </tr>
      </tbody>
  </table>
  <input type="submit">Save</input>
</form>

What did I forget? 我忘记了什么?

You should use the following syntax : 您应该使用以下语法:

<tr th:each="myObj, rowStat : *{data}">

and then set the input fields using : 然后使用设置输入字段:

th:field="*{data[__${rowStat}.index}__].myField}"

That will bind your MyForm with the input data. 这会将MyForm与输入数据绑定。

More examples can be found here Thymeleaf and forms 更多的例子可以在这里找到Thymeleaf和形式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM