Reputation: 3058
I need to render radio buttons using an enumeration in my MVC2 application.
Can anybody help me out resolve this issue.
Thanks for sharing your wisdom.
Upvotes: 1
Views: 286
Reputation: 22016
You will need to use the GetNames function:
<% foreach (string name in Enum.GetNames(typeof(EnumType)))
{
%>
<input type="radio" value="<%=name %>" name="instanceName"/>
<%
} %>
then on the server side you can use Enum.Parse function to parse the string back into an enum.
UPDATE
Jace is correct to comment that the default model binder will map the string to the enum for you.
Upvotes: 5
Reputation: 3635
I think you want to use reflection. You get all the members of the enum, and for each you create an input element but what you need to know is that the following code segment uses reflection to list all the elements in an enumeration.
public enum JuiceTypes
{
Apple,
Orange,
Pineapple,
Peach,
HoneyTea,
Tomato
}
string[] juiceTypes = Enum.GetNames(typeof(JuiceTypes));
foreach (string juice in juiceTypes)
{
Console.WriteLine(juice);
//in MVC you need to use Response.WriteLine("<input type=\"radio\" value=\"+juice+"\"/>");
}
Upvotes: 1