简体   繁体   中英

How to populate a combo box with an ArrayList in Thymeleaf?

I have an ArrayList that contains objects, I want to populate the drop down box with each object (subject) in the arraylist.

At the moment my code is adding the ArrayList to the combo box however it's displaying everything in the ArrayList on each line rather than it displaying one subject per line. (See image below)

在此处输入图片说明

How do I get it to display each object in the arraylist?

My controller

@GetMapping("/addexam")
public String showExamForm(Model model) {
    Authentication loggedInUser = SecurityContextHolder.getContext().getAuthentication();
    String email = loggedInUser.getName();
    User user = userRepository.findByEmailAddress(email);
    ArrayList<String> subjects = new ArrayList<String>();
    for (Subject sub : user.getSubject()) {
        subjects.add(sub.getSubjectName());
    }
    model.addAttribute("subjects", subjects);
    return "addExam";
}

HTML file

<select class="form-control" id="subjectOrder" name="subjectOrder">
    <option value="">Select subject</option>
    <option th:each="Subject : ${subjects}" th:value="${subjects}" th:text="${subjects}"></option>
</select>

You're html section seems to be wrong as you're using the whole list at th:value and th:text (and so get all the entries in each line).

Should be

<option th:each="Subject : ${subjects}"
th:value="${Subject}"
th:text="${Subject}"></option>

imo. Notice the use of ${Subject} rather than ${subject[s]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM