Domanda

I have the following ViewModel that sets a list of items to display in my drop down.

myController/Index

// set view model list of items to populate in drop down...viewModel contains listItems as   
   List<String>
viewModel.setlistitems(//list retrieved 3rd party);
// add view model to model to display items in drop down list viewModel.getlistitems() returns List<String>
model.addAttribute("viewModel", viewModel);  

Then I have the drop down list in my index.jsp which populates the list fine:

 <form class="form-horizontal" action="myController/indexSubmit" method="post">
    <select name="selectList" class="form-control" placeholder=".input-medium" height>
        <c:forEach items="${viewModel.getlistitems()}" var="item" varStatus="count"> 
            <option value="${count.index}">${item }</option>
        </c:forEach>
    </select>   
    <button type="submit" class="btn btn-primary btn-medium">Submit</button>   
</form>  

Submit posts back and I get the index of the selected drop down just fine within "selectList". However, when i try to get the list items from my view model it's null?

@RequestMapping(value="indexSubmit", method = RequestMethod.POST)
  public String indexSubmit( @RequestParam String selectList, 
      @ModelAttribute("viewModel") ViewModel viewModel, ModelMap model) {

    System.out.println("Selected Item: " + selectList);  // returns the index fine
    System.out.println("Items: " + viewModel.getlistitems());  // returns NULL!!  this was the same list call that populated the drop down
    return "redirect:/index"; 
} 

How can I 1) return a list<string> back from within my view model to get the list of items to reference via the selected item index to return as query param or 2) how can get the actual string literal of the selected item instead of the index?

Thx!

È stato utile?

Soluzione

model.addAttribute("nameOfList", viewModel.getlistitems());

then in your form use the spring tag lib

<form:select path="modelPath">
    <form:option value="0" label="Select an Option" />
    <form:options items="${nameOfList}" />
</form:select>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top