【问题标题】:How do I populate a drop down with a list using thymeleaf and spring如何使用 thymeleaf 和 spring 使用列表填充下拉列表
【发布时间】:2016-10-09 11:25:15
【问题描述】:

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

控制器类

@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/控制器应该是什么样子?

提前致谢!

【问题讨论】:

    标签: java html spring thymeleaf


    【解决方案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>
    

    【讨论】:

    • th:text="select operator" 给出错误“TemplateProcessingException:无法解析为表达式”。无论如何+1 ;)
    • 如果列表大小只有 1,我如何选择默认的第一个值 onload?
    【解决方案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>
    

    我的结果

    Image - tymeleaf dropdown from model

    【讨论】:

    • 你的列表 test = new ArrayList();什么都不做,因此,没有必要编写这样的虚假代码。然而,这些代码行将为您解决问题: List tests = testRepository.findAll(); model.addAttribute("测试", 测试);此外,最好使用您的服务而不是使用存储库。
    • 你必须使用列表吗?
    • 是的,我使用了一个列表。
    • 好的,对于 POST,如何将所选项目从下拉列表保存到数据库?
    【解决方案3】:

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

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

    【讨论】:

    • 我按照 Raneer 的说法让它工作了,但这并不容易。我认为复杂性取决于一个人如何到达创建数组列表的原始列表。
    • 如果国家/地区列表中不包含 th:field 值,我们将如何提供附加选项?谢谢
    【解决方案4】:

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

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

    【讨论】:

      【解决方案5】:

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

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-23
        • 2020-10-03
        • 2014-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-05
        • 2020-04-08
        相关资源
        最近更新 更多