ASP.NET: show / hide switch list items programmatically

I need to know how to do something that would intuitively do the following if it worked (imagine useGreek() and useNato() states that will be discussed once at boot or postback):

 <asp:radioButtonList id="rbl" runat="server" autoPostBack="true"> <asp:listItem value="alpha" text="Alpha" /> <% if(useGreek()) { %> <asp:listItem value="beta" text="Beta" /> <asp:listItem value="gamma" text="Gamma" /> <% } else if(useNato()) { %> <asp:listItem value="bravo" text="Bravo" /> <asp:listItem value="charlie" text="Charlie" /> <% } %> <asp:listItem value="delta" text="Delta" /> </asp:radioButtonList> 

(It will already be obvious that I’m usually not asked to write for IIS.)

In any case, ASP.NET does not like code that alternates with list items, so this is non-go. I guess there is some kind of approach in C # to handle this, but I have been trying for several days with no luck.

Also, to be clear, I am looking for a server-side solution. I am good at jQuery, but we try to keep most of the processing of this particular form from the client.

Thanks, and party on.

+1
source share
1 answer

No C #, but I think you understand what I mean:

in codebehind page_load:

 If Not IsPostBack Then Me.rbl.Items.Add(New ListItem("Alpha", "alpha")) If (useGreek()) Then Me.rbl.Items.Add(New ListItem("Beta", "beta")) Me.rbl.Items.Add(New ListItem("Gamma", "gamma")) ElseIf (useNato()) Then Me.rbl.Items.Add(New ListItem("Bravo", "bravo")) Me.rbl.Items.Add(New ListItem("Charlie", "charlie")) End If Me.rbl.Items.Add(New ListItem("Delta", "delta")) End If 

If you need to check every answer because the state can change quickly, you can add Me.rbl.Items.Clear() to the beginning and remove the PostBack check.

EDIT: C #

 if (!IsPostBack) { this.rbl.Items.Add(new ListItem("Alpha", "alpha")); if ((useGreek())) { this.rbl.Items.Add(new ListItem("Beta", "beta")); this.rbl.Items.Add(new ListItem("Gamma", "gamma")); } else if ((useNato())) { this.rbl.Items.Add(new ListItem("Bravo", "bravo")); this.rbl.Items.Add(new ListItem("Charlie", "charlie")); } this.rbl.Items.Add(new ListItem("Delta", "delta")); } 

Because I'm not sure that you already know the codebehind model, look at the following link: MSDN: Codebehind and compilation in ASP.NET 2.0

+2
source

All Articles