Reputation: 1800
I have a group of radio buttons that is dynamically generated during the page load. Can't think of the best way to get the selected radio button in C#.
Any Ideas?
Upvotes: 1
Views: 1717
Reputation: 39
Suppose you have 3 groups: Group1 has 4 variables, Group2 has 2 variables and Group3 has 3 variables.
First you need an array to store these names:
public string mygrouparray = new string[3];
mygrouparray[0] = Group1;
mygrouparray[1] = Group2;
mygrouparray[2] = Group3;
Next, you need a jagged array to store the variable names from each group:
public string[][] vararray = new string[3][];
vararray[0] = new string[4];
vararray[1] = new string[2];
vararray[2] = new string[3];
Put the variables in the vararray:
vararray[0][0] = g1var1;
vararray[0][1] = g1var2;
...
vararray[2][1] = g3var2;
vararray[2][2] = g3var3;
You also need an array to keep track of the number of variables in each group:
public int nvararray = new int[3]
nvararray[0] = 4;
nvararray[1] = 2;
nvararray[2] = 3;
As you may know, each radio button group needs a unique name. Here is how to set it up on your cshtml page:
<form method="post">
@for (int i = 0; i < 3; i++)
{
<p><b>@Model.mygrouparray[i]</b></p>
@for (int j = 1; j <= nvararray[i]; j++)
{
<p><input type="radio" [email protected]("group_", Convert.ToString(@i)) value=@j>@Model.vararray[i][j-1]</p>
}
}
<p><button type="submit">Submit</button></p>
</form>
The reason to start j=1 is because, if a person does not choose a radio button, it returns a value of zero.
In order to receive the chosen variables, you need an array for that:
public int varchoosearray = new int[3];
Now you can receive the variables:
for (i = 0; i < 3; i++)
{
varchoosearray[i] = Convert.ToInt32(Request.Form[String.Concat("group_", Convert.ToString(i))])-1;
}
If a person does not choose a radio button, you will note that it will submit a value of -1 into varchoosearray and you can flag that.
Upvotes: 0