如何将所选下拉值传递给Thymelaf中的控制器



如何将下拉列表的选定值(Thymelaf(传输到控制器(Spring(?列表本身是正常形成的,问题出在按钮上。

控制器:

@RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (@RequestParam String task) {
System.out.println(task);
return "redirect:/courier";
}

视图:

<div class="taskList" th:object="${task}">
<select class="form-control" id="courierTasks" name="courierTasks">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<form th:action="@{/courier/notInTime}" method="post">
<input type="hidden"/>
<button type="submit">Not in time</button>
</form>
</div>

您只需在控制器中将@RequestParam更改为@Valid,然后在Thymelaf中将您的选择名称更改为"task",它应该在表单包装中。

@RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (@Valid String task) {
System.out.println(task);
return "redirect:/courier";
}
<select class="form-control" id="courierTasks" name="task">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>

您应该在表单中添加select标记,以便表单提交task

尝试以下

<form th:action="@{/courier/notInTime}" method="post">
<div class="taskList" th:object="${task}">
<select class="form-control" id="courierTasks" name="courierTasks">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<input type="hidden"/>
<button type="submit">Not in time</button>
</div>
</form>

请注意,您可以编写一个简单的javascript函数,以便表单提交task,即使它在表单之外,但是,在您的情况下,我看不出不在表单中添加select的原因。

@Sopheak@Ioannis many thx。

控制器:

@RequestMapping(value="courier/notInTime", method = RequestMethod.POST)
public String deleteUser (@Valid String task) {
System.out.println(task);
return "redirect:/courier";
}

视图:

<form th:action="@{/courier/notInTime}" method="post">
<select class="form-control" id="task" name="task">
<option value="">Select task for disable</option>
<option th:each="task : ${tasks}"
th:value="${task}"
th:text="${task}">
</option>
</select>
<button type="submit">Not in time</button>
</form>

最新更新