I am trying to load drop down list using ArrayList in Springboot as i am new to springboot.
I have tried but not working as expected.
Please find the code which i have tried as below:
@Controller
public class DemoController {
@GetMapping("/create")
public String create(Model model) {
model.addAttribute("create", new Demo());
return "create";
}
public void countriesList(Model model) {
List<String> countryList = new ArrayList<>();
countryList.add("US");
countryList.add("UK");
model.addAttribute("countries", countryList);
}
}
<form action="#" th:action="@{/create}" th:object="${create}" method="post">
<select th:field="*{country}">
<option value=""> -- </option>
<option th:each="country : ${countries}" th:value="${country}" th:text="${country}"></option>
</select>
</form>
Finally no errors but only loading in dropdown list with --
and not loading the countries.
Please help me on this.
You never called your function for adding countries to the model...
@Controller
public class DemoController {
@GetMapping("/create")
public String create(Model model) {
model.addAttribute("create", new Demo());
countriesList(model); // this line is needed
return "create";
}
private void countriesList(Model model) {
List < String > countryList = new ArrayList < > ();
countryList.add("US");
countryList.add("UK");
model.addAttribute("countries", countryList);
}
}
try with this code block
<span th:each="country:${countries}" th:remove="tag">
<option th:value="${country}" th:text="${country}"></option>
</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.