问题描述
美好的一天,
我正在尝试通过 Hashmap 显示选择字段选项并获取发布的值.
I am trying to show the select field options by Hashmap and get the posted value back too.
我使用了两个类,一个用于控制器,另一个用于模型.
I am using two classes one is for controller and the other for model.
public class MyForm {
private int id;
private Map<String, String> list;
//getter setters
}
@Controller
public class MyController {
@GetMapping("/create")
public String showForm(MyForm myForm) {
Map<String, String> list = new HashMap();
list.put("US", "United States")
list.put("UK", "United Kingdom")
return "myview"
}
@PostMapping("/create")
@ResponseBody
public String showForm(MyForm myForm) {
return "id: " + myform.getId() + " list: " + myform.getList();
}
}
这是模板.
<form th:action="@{/create}" th:object="${myForm}" method="POST">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p>
Countries :
<select id="list" name="list">
<option th:each="c : *{list}" th:value="${c.key}" th:text="${c.value}"></option>
</select>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
当我打开 localho:8080/test 时,它会向我显示一个文本字段并选择包含美国和英国两个选项的文件.
when i open localho:8080/test its show me a text field and select filed with both options united states and united kingdom.
在 id 字段中输入 1 并选择英国后,我按下提交按钮,它显示
After typing 1 in id field and choosing united kingdom and then i press submit button it shows
1, null
请帮我解决这个问题.
谢谢.
推荐答案
没关系.
我通过添加额外的字段来做到这一点.
I have done it by adding extra field.
List<String> country;
在 MyForm 模型类中,并为 thymeleaf 中的选择字段指定名称 country.
in MyForm model class and assigned name country to the select field in thymeleaf.
<select id="country" name="country">
<option th:each="c : *{list}" th:value="${c.key}" th:text="${c.value}"></option>
</select>
这篇关于如何使用spring和thymeleaf获取Hashmap中的发布值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!