如何以Spring MVC形式设置所选值:从控制器中选择? [英] How do I set the selected value in a Spring MVC form:select from the controller?

查看:84
本文介绍了如何以Spring MVC形式设置所选值:从控制器中选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中:

@Controller
public class UserController {

    @RequestMapping(value="/admin/user/id/{id}/update", method=RequestMethod.GET)
    public ModelAndView updateUserHandler(@ModelAttribute("userForm") UserForm userForm, @PathVariable String id) {

        Map<String, Object> model = new HashMap<String, Object>();
        userForm.setCompanyName("The Selected Company");
        model.put("userForm", userForm);

        List<String> companyNames = new ArrayList<String>();
        companyNames.add("First Company Name");
        companyNames.add("The Selected Company");
        companyNames.add("Last Company Name");

        model.put("companyNames", companyNames);

        Map<String, Map<String, Object>> modelForView = new HashMap<String, Map<String, Object>>();
        modelForView.put("vars", model);

        return new ModelAndView("/admin/user/update", modelForView);
    }
}

我视图中的选择表单字段:

The select form field in my view:

<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="id" itemLabel="companyName" />
</form:form>

据我了解,表单支持bean将基于表单中的modelAttribute属性进行映射.我显然在这里丢失了一些东西.

It was my understanding that the form backing bean would be mapped based upon the modelAttribute attribute in the form. I'm obviously missing something here.

推荐答案

问题似乎与我的设置无关.问题在于,itemValue设置为公司id属性,而对窗体支持bean上的公司名称属性进行了比较.因此两者不相等,因此没有选择任何项目.

It appears the issue was not related to my setup. The problem was that the itemValue was set to the company id property, while the comparison was being done to the company name property on my form backing bean. So the two were not equal, and therefore, no item was set to selected.

上面的代码可以很好地工作,并且在userForm中为特定属性设置值将把该值设置为在选择表单字段中选择的值,只要item集合中一项的值等于表单价值.我将表单字段更改为如下所示,它提取了CompanyName而不是ID.

The above code works just fine, and setting the value in the userForm for a particular property will set that value as selected in select form fields so long as the value of one of the items in the items collection is equal to the form value. I changed my form field to look like this, which pulls the companyName instead of the id.

<form:form method="post" action="/admin/user/update.html" modelAttribute="userForm">
<form:select path="companyName" id="companyName" items="${vars.companyNames}" itemValue="companyName" itemLabel="companyName" />
</form:form>

这篇关于如何以Spring MVC形式设置所选值:从控制器中选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆