【问题标题】:Dropdown list using Thymeleaf in SpringBoot在 Spring Boot 中使用 Thymeleaf 的下拉列表
【发布时间】:2019-09-24 18:01:59
【问题描述】:

我正在尝试在 Springboot 中使用 ArrayList 加载下拉列表,因为我是 springboot 新手。

我已经尝试过,但没有按预期工作。

请找到我尝试过的代码如下:

Java 代码:

@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);

       }
}

HTML:

<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>

最后没有错误,但只在下拉列表中加载-- 而没有加载国家/地区。

请帮帮我。

【问题讨论】:

  • 请添加您遇到的错误
  • 我已经尝试过,但没有按预期工作并出现错误。 为什么你认为在你的问题中不包括这些错误是个好主意?
  • 此外,您没有向模型添加任何内容。
  • 如何添加模型..请帮助我,因为我是 Springboot 的新手。谢谢@Antoniossss
  • countryList 必须添加到模型中,以便 thymeleaf 可以访问它。 model.addAttribute("countries", countryList);

标签: java spring-boot thymeleaf


【解决方案1】:

您从未调用过将国家/地区添加到模型中的函数...

@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);

 }
}

【讨论】:

  • 添加此行后 - countriesList(model); 工作没有任何问题。谢谢@Nodir Rashidov
  • 请帮助我在下拉列表中选择值时如何调用方法?谢谢@Nodir Rashidov
【解决方案2】:

试试这个代码块

 <span th:each="country:${countries}" th:remove="tag">
          <option th:value="${country}" th:text="${country}"></option>
    </span>

【讨论】:

  • 没有错误,但页面上没有任何内容,因为页面上没有显示下拉列表。请帮助我。谢谢@pantha istiaque
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多