2016-06-09 58 views
7

我需要使用字符串列表中的所有值填充下拉列表。如何使用百里香和彈簧填充列表下拉列表

控制器類

@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 /控制器模樣添加所有的元素的列表作爲下拉選項?

提前致謝!

回答

7

這是我如何填充下拉列表。我認爲這可能有助於你對此有所瞭解。

控制器

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" th:text="select operator" ></option> 
    <option th:each="operator : ${operators}" th:value="${operator.id}" th:text="${operator.operatorName}"></option> 
    </select> 
</div> 
3

首先感謝你的問題和答案!我已經完成了這個解決方案。

我的模型

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

我的結果

Image - tymeleaf dropdown from model