如何在Wicket的RadioChoice onChange事件中获取当前选中值?
解决Wicket RadioChoice Ajax onChange事件获取选中值的问题
嘿,我看到你在Wicket里用RadioChoice的Ajax change事件获取选中值时卡壳了——虽然onUpdate已经触发,但不知道怎么拿到选中的内容对吧?其实这事儿很简单,有两种直接的方式可以搞定:
方法1:通过绑定的模型属性获取
你已经用PropertyModel<String>(this, "selected")把RadioChoice绑定到了当前类的selected属性上,而AjaxFormComponentUpdatingBehavior会自动把选中的值更新到这个绑定的属性里。所以在onUpdate方法里,直接调用你类里的getSelected() getter方法就能拿到最新值了:
RadioChoice<String> radioChoice = new RadioChoice<>("radio", new PropertyModel<>(this, "selected"), this.radioChoiceList); radioChoice.add(new AjaxFormComponentUpdatingBehavior("change") { @Override protected void onUpdate(AjaxRequestTarget target) { String selectedValue = getSelected(); // 确保你的类有对应的getSelected()方法 System.out.println("ajax here! 选中的值是:" + selectedValue); } }); Form<?> form = new Form<Void>("form"); add(form); form.add(radioChoice);
方法2:直接从RadioChoice组件获取
因为AjaxFormComponentUpdatingBehavior会更新组件的模型,所以你也可以直接通过组件的getModelObject()方法获取选中值。如果是Java 8之前的版本,需要把radioChoice声明为final(Java 8及以后可以不用,因为它是effectively final):
final RadioChoice<String> radioChoice = new RadioChoice<>("radio", new PropertyModel<>(this, "selected"), this.radioChoiceList); radioChoice.add(new AjaxFormComponentUpdatingBehavior("change") { @Override protected void onUpdate(AjaxRequestTarget target) { String selectedValue = radioChoice.getModelObject(); System.out.println("ajax here! 选中的值是:" + selectedValue); } }); Form<?> form = new Form<Void>("form"); add(form); form.add(radioChoice);
原理说明
AjaxFormComponentUpdatingBehavior的核心作用就是在触发事件时,将前端提交的选中值同步更新到组件的模型(包括你绑定的PropertyModel)中,然后才会执行onUpdate方法。所以这时候不管是从绑定的类属性还是组件模型里拿值,都是最新的选中状态啦。
内容的提问来源于stack exchange,提问作者Lars Karlsen
相关产品推荐
相关产品推荐

