0

我有 2 个下拉列表:国家和州。我想在更改国家列表的选择时重新加载州列表。我尝试了如何在 selectOneMenu 中将值传递给侦听器。但是,我的代码中的更改事件不起作用。谁能帮助我?谢谢你。

国家和州下拉菜单

<h:selectOneMenu id="ddlCountry" value="#{Bean.companyCountry}" >
    <f:selectItems value="#{Bean.countries}" var="country" itemValue="#{country.value}" itemLabel="#{country.name}" />
    <f:ajax event="change" listener="#{Bean.loadStates}" render="ddlState" execute="@this"/>
</h:selectOneMenu>

<h:selectOneMenu id="ddlState" value="#{Bean.companyState}">
    <f:selectItems value="#{Bean.states}" var="state" itemValue="#{state.value}" itemLabel="#{state.name}" />
</h:selectOneMenu>

Java Bean 类sscce

private ArrayList<State> states;
public ArrayList<State> getStates() {
    return states;
}
public void loadStates(AjaxBehaviorEvent event) {
    states = new ArrayList<State>();
    if(companyCountry.equals("USA")){
        states.add(new State("1","UT"));
        states.add(new State("2","WA"));
        states.add(new State("3","CA"));
    }
}

jsf ajax 监听器仍然无法在我的项目中工作。所以我使用了 primefaces 标签,它可以解决我的问题。

<h:selectOneMenu id="ddlCountry" value="#{Bean.companyCountry}"  >
    <f:selectItems value="#{Bean.countries}" var="country" itemValue="#{country.value}" itemLabel="#{country.name}" />
    <p:ajax event="valueChange" update="ddlState" process="@this"/>
</h:selectOneMenu>

<h:selectOneMenu id="ddlState" value="#{Bean.companyState}">
    <f:selectItems value="#{Bean.states}" var="state" itemValue="#{state.value}" itemLabel="#{state.name}" />
</h:selectOneMenu>

Java Bean 类sscce

private ArrayList<State> states;
public ArrayList<State> getStates() {
    states = new ArrayList<State>();
    if(companyCountry.equals("USA")){
        states.add(new State("1","UT"));
        states.add(new State("2","WA"));
        states.add(new State("3","CA"));
    }
    else{
        states.clear();
    }
    return states;
}
4

1 回答 1

0

将您的 bean 范围从更改@RequestScoped@ViewScoped

否则,在您调用该listener方法后,将创建一个新的 bean 实例,而您的另一个实例h:selectOneMenu将填充空值。

于 2012-12-24T10:16:32.927 回答