如何使用百里香和弹簧用列表填充下拉列表

2022-09-01 12:46:39

我需要用字符串列表中的所有值填充一个下拉列表。

控制器类

@RequestMapping(value = "/generateIds", method = RequestMethod.GET)
public String launchPage(Model model) {
    List<Municipality> municipalities = rCountryService.finaAllMunicipalities();
    //assume the list is populated with values
    List<String> countryName = new ArrayList<String>();
    for(int i=0; i<municipalities.size(); i++) {
        countryName.add(municipalities.get(i).getCountry().toString());
    }
    model.addAttribute("countryName ", countryName );

    return "generateIds";
}

我不知道从哪里开始HTML,所以我从这个开始

<select th:field="*{countryName }">
    <option value="default">Select a country</option>
    <option th:each="${countryName }" th:value="${countryName }"th:text="${countryName }"/>
</select>

将列表的所有元素添加为下拉选项时,我的html/控制器应该是什么样子?

提前致谢!


答案 1

这就是我填充下拉列表的方式。我认为这可能有助于您了解它。

控制器

List<Operator> operators =  operatorService.getAllOperaors()
model.addAttribute("operators", operators);

  @Entity
  @Table(name = "operator")
  public class Operator {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    @JsonIgnore
    private Long id;

    @NotBlank(message="operator Name cannot be empty")
    @Column(name = "operator_name", nullable = false)
    private String operatorName;

    getters and setters ...

}   

视图

<div class="form-group blu-margin">
    <select class="form-control" th:field="${operator.opeId}"  id="dropOperator">
    <option value="0">select operator</option>
    <option th:each="operator : ${operators}" th:value="${operator.id}" th:text="${operator.operatorName}"></option>
    </select>
</div>

答案 2

首先感谢您的提问和回答!我已经完成了这个解决方案。

我的模特

@Entity
@Table(name = "test")
public class Test {

    @Id
    private String testCode;
    private String testName;
    private int price;

    public Test() {}

    public Test(String testCode, String testName, int price) {
        this.testCode = testCode;
        this.testName = testName;
        this.price = price;
    }

    public String getTestCode() {
        return testCode;
    }

    public String getTestName() {
        return testName;
    }

    public int getPrice() {
        return price;
    }
}

我的观点

    List<Test> test = new ArrayList<>();
    model.addAttribute("test", test);
    List<Test> tests = testRepository.findAll();
    model.addAttribute("tests", tests);

我的 HTML

<div class="col-lg-3" th:object="${test}">
    <select class="form-control" id="testOrder" name="testOrder">
        <option value="">Select Test Order</option>
        <option th:each="test : ${tests}"
                th:value="${test.testCode}"
                th:text="${test.testCode}+' : '+${test.testName}"></option>
    </select>
</div>

我的结果

图像 - 从模型下拉列表