views:

2106

answers:

3

I'm trying to render a radio button list in MVC 2 RC 2 (C#) using the following line:

<%= Html.RadioButtonFor(model => Enum.GetNames(typeof(DataCarry.ProtocolEnum)),
                        null) %>

but it's just giving me the following exception at runtime:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Is this possible and if so, how, please?

+1  A: 

Try GetValues instead

RailRhoad
+5  A: 

You can create a template called "Enum" in /Views/Shared/EditorTemplates/Enum.ascx

With the following content:

<%= Html.DropDownList(string.Empty, Enum.GetNames(Model.GetType()).ToList().ConvertAll(e => new SelectListItem() { Text = e.ToString(), Value = e , Selected = e.Equals(Model.ToString())}))  %>

This just enumerates the enum values.

You can call this with

Html.EditorFor(m => m.YourEnumProperty, "Enum" /*The name of the template*/)
amarsuperstar
Of course you can change it from DropDownList -- the generation of the select list is the main part. :-)
amarsuperstar
I don't see an equivalent method on `Html.RadioButtonFor`. It seems that helper method only takes one value. Is there an alternative that does what the OP asks?
Drew Noakes
+3  A: 

The accepted answer is good, but you can avoid the ToList() call by doing the following:

<%= Html.DropDownList(string.Empty,
                      Enum.GetNames(Model.GetType())
                          .Select(e => new SelectListItem() {
                              Text = e.ToString(),
                              Value = e,
                              Selected = e.Equals(Model.ToString())
                          })
                      ) %>
dotjosh
+1, This is a much cleaner piece of code.
Alastair Pitts
How does this create a radio list? This creates a `<select>` instead, right?
Drew Noakes
I don't see how this answers the OP's question. He asked for `RadioButtonFor`, not `DropDownList`. -1
Josh E