【问题标题】:How to get back list for drop down as @ModelAttribute for Spring mvc Post?如何以@ModelAttribute for Spring mvc Post的形式返回下拉列表?
【发布时间】:2013-08-28 06:43:44
【问题描述】:

我有以下 ViewModel 设置要在我的下拉列表中显示的项目列表。

我的控制器/索引

// 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);  

然后我的 index.jsp 中有一个下拉列表,它可以很好地填充列表:

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

提交回帖,我会在“selectList”中很好地获得所选下拉列表的索引。但是,当我尝试从我的视图模型中获取列表项时,它是空的吗?

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

我怎样才能 1)从我的视图模型中返回 list&lt;string&gt; 以通过所选项目索引获取要引用的项目列表以作为查询参数返回或 2)如何获取所选项目的实际字符串文字项目而不是索引?

谢谢!

【问题讨论】:

    标签: jsp spring-mvc jsp-tags query-parameters


    【解决方案1】:
    model.addAttribute("nameOfList", viewModel.getlistitems());
    

    然后在你的表单中使用 spring 标签库

    <form:select path="modelPath">
        <form:option value="0" label="Select an Option" />
        <form:options items="${nameOfList}" />
    </form:select>
    

    【讨论】:

    • 感谢您的回复。所以,我正在使用引导程序。这会改变表格吗?另外,我需要为标签库包含什么来获取 form:xx 注释?
    • 没有。只需在&lt;form:select path="modelPath" cssClass="form-horizontal"&gt;之类的表单上添加class,然后spring的标签库就像JSTL一样,将其导入页面顶部
    • 再次感谢 Bk Santiago!
    猜你喜欢
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-25
    • 1970-01-01
    • 2013-05-23
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多