如何将枚举传递给 Html.RadioButtonFor 以获取 MVC 2 RC 2、C# 中的单选按钮列表如何将、单选、按钮、列表

2023-09-06 21:48:01 作者:毁我爱他,你真TM奇葩

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:

怎么给radio加按钮特效

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?

解决方案

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*/)