Unable to get Spring to populate a select box with options

时间:2016-02-12 20:52:25

标签: html spring thymeleaf

I've tried several different options but I cannot seem to be able to populate a dropdown list unless I use static html data which i'm trying to avoid.

My simple case is:

Generate ModelAndView to be rendered, use value from object as the list of options and tadaaa.

Simple controller:

    my_is_int(1.0);   // TRUE
    my_is_int("1.0"); // FALSE

View: I've tried both the Spring variant of having form:select and form:options and the thyme leaf version - neither of which are rendering.

@RequestMapping("/")
public ModelAndView indexPage(HttpServletRequest request)
        throws Exception {

    ArrayList<String> numberOfKids = new ArrayList<String>();
    numberOfKids.add("-Small People-");
    numberOfKids.add("0");
    numberOfKids.add("1");
    numberOfKids.add("2");

    ModelAndView modelAndView = new ModelAndView("index");
    modelAndView.addObject("numberOfKids", numberOfKids);

    return modelAndView;
}

in the console, there are no values and it also has a class of display: none which is odd as I haven't added it.

Any hero appreciated, I imagine its something small as I'm rushing about but can't bring the focus back in - and my debugger has died a slow painful death which isn't helping. :(

Edit: Weirder still... If I copy that block into another select, the second one populates...

<div class="form-group">
    <form:select name="numberOfKids" id="numberOfKids" tabindex="3">
        <option th:each="number : ${numberOfKids}"
            th:value="${number}"
            th:text="${number}">
        </option>
     </form:select>
</div>

3 个答案:

答案 0 :(得分:2)

您不应在Thymeleaf模板中将JSP标记用作<form:select/>,因为Thymeleaf无法处理此标记。而只使用简单的html <select/>标记:

<div class="form-group">
    <select name="numberOfKids" id="numberOfKids" tabindex="3">
        <option th:each="String : ${numberOfKids}" th:value="${String}" th:text="${String}">
        </option>
    </select>
</div>

答案 1 :(得分:1)

thymeleaf不理解<form:select... />(此标记是JSP taglib)。相反,您应该使用<select th:field="*{numberOfKids}">。有关详细信息read this

答案 2 :(得分:0)

Try this:

@Model.Description

Usually it's used with a Map instead of List, so you will have the text and value filled in.