我正在尝试访问apache wicket中DropDownChoices中用户选择的值。 我将AjaxFormComponentUpdatingBehavior添加到DropDownChoices元素。我在onUpdate行为方法中作为选定选项获取null。我试图通过不同的方式访问选定的值,如下面的代码所示,但在debuing时仍然为null。
private String selectedMake;
private final Map<String, List<String>> modelsMap = new HashMap<String, List<String>>(); // map:company->model
modelsMap.put( "AUDI", Arrays.asList( "A4", "A6", "TT" ) );
modelsMap.put( "CADILLAC", Arrays.asList( "CTS", "DTS", "ESCALADE", "SRX", "DEVILLE" ) );
modelsMap.put( "FORD", Arrays.asList( "CROWN", "ESCAPE", "EXPEDITION", "EXPLORER", "F-150" ) );
IModel<List<? extends String>> makeChoices = new AbstractReadOnlyModel<List<? extends String>>() {
@Override
public List<String> getObject() {
return new ArrayList<String>( modelsMap.keySet() );
}
};
lastDropDownChoice = new DropDownChoice<String>( "daynamicTimeConstrains",
new PropertyModel<String>( this, "selectedMake" ), makeChoices );
lastDropDownChoice.add( new AjaxFormComponentUpdatingBehavior( "onchange" ) {
@Override
protected void onUpdate( AjaxRequestTarget target ) {
// Getting this as null
System.out.println( selectedMake );
// Getting this as null
getFormComponent().getModel().getObject();
}
} );
答案 0 :(得分:1)
使用OnChangeAjaxBehavior。这段代码适合我:
public class HomePage extends WebPage {
private String text;
public String getText() {
return text;
}
private static final List l = Arrays.asList("a", "b", "c");
public HomePage(final PageParameters parameters) {
super(parameters);
add(ddc());
}
private DropDownChoice ddc(){
DropDownChoice ddc = new DropDownChoice("ddc", new PropertyModel(this, "text"), l);
ddc.add(new OnChangeAjaxBehavior() {
@Override
protected void onUpdate(AjaxRequestTarget target) {
System.out.println(getComponent().getDefaultModelObjectAsString());
System.out.println("getText: " + getText());
}
});
return ddc;
}
}
答案 1 :(得分:0)
我过去遇到过一些问题,主要是文本框,因为在提交表单之前不会处理输入。也就是说,当属性模型似乎没有正确更新时,我将使用getFormComponent()。getConvertedInput()并将其转换为AjaxFormComponentUpdatingBehavior(),如下所示:
lastDropDownChoice.add( new AjaxFormComponentUpdatingBehavior( "onchange" ) {
@Override
protected void onUpdate( AjaxRequestTarget target ) {
String input = (String) getFormComponent().getConvertedInput();
System.out.println( input );
selectedModel = input;
}
} );
我很想听听其他人这种方法可能有什么缺点,但它似乎比其他许多看似可能使用的潜在选项更可靠。
顺便说一下,我通常总是创建一个新的IChoiceRenderer()并覆盖抽象值,以便能够传递对象而不是字符串,并能够按照我的要求显示它们如下所示:
lastDropDownChoice = new IndicatingDropDownChoice("daynamicTimeConstrains", new PropertyModel(this, "selectedMake"), makeList, new IChoiceRenderer() {
@Override
public Object getDisplayValue(Object o) {
return makeList.indexOf(selectedMake) + "." + o.toString();
}
@Override
public String getIdValue(Object o, int i) {
return o.toString();
}
});