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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37715276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:36:16  来源:igfitidea点击:

How do I populate a drop down with a list using thymeleaf and spring

javahtmlspringthymeleaf

提问by Roman Paolucci

I need to populate a drop down with all the values within a list of strings.

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

Controller Class

控制器类

@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";
}

I didn't know where to start for the HTML so I started with this

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

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

What should my html/controller look like to add all of the elements of the list as drop down options?

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

Thanks in advance!

提前致谢!

采纳答案by Hasitha Diluka

This is how I populate the drop down list.I think it may help to you get some idea about it.

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

Controller

控制器

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

Model

模型

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

}   

View

看法

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

回答by Thanongsak Chamung

First thank to your question and answer! I've done with this solution.

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

My Model

我的模特

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

My View

我的看法

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

My HTML

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

My Result

我的结果

Image - tymeleaf dropdown from model

图像 - 来自模型的 tymeleaf 下拉菜单

回答by Leemarshn

You only need this code in your view.

您只需要在您的视图中使用此代码。

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

回答by Ranveer Singh

For generating dropdown for the list of String returned in model you just need to use these lines. You don't need to create any model class with extra getter and setter methods. Your code is correct, you just missed the variable name for storing the value returned in countryName list in th:each.

要为模型中返回的字符串列表生成下拉列表,您只需要使用这些行。您不需要使用额外的 getter 和 setter 方法创建任何模型类。您的代码是正确的,您只是错过了用于存储 th:each 中 countryName 列表中返回值的变量名称。

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

回答by Senthuran

I have implemented a similar where i need to populate the dropdown from the database. For that I retrieved the data from the controller as below

我已经实现了一个类似的地方,我需要从数据库中填充下拉列表。为此,我从控制器中检索了数据,如下所示

@GetMapping("/addexpense")
public String addExpense(Expense expense,Model model){
    model.addAttribute("categories",categoryRepo.findAll());
    return "addExpense";
}

Then in the thymeleaf I have used the below code.

然后在百里香叶中我使用了下面的代码。

<div class="form-group col-md-8">
<label  class="col-form-label">Category </label>
<select  id="category" name="category" th:field="*{category.id}" >
<option th:each="category : ${categories}" th:value="${category.id}" th:utext="${category.name}"/>
</select>
</div>