How to pass an enum to Html.RadioButtonFor to get a list of radio buttons in MVC 2 RC 2, C#

流过昼夜 提交于 2019-12-03 09:45:04

问题


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:


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



回答2:


Try GetValues instead



来源:https://stackoverflow.com/questions/2222743/how-to-pass-an-enum-to-html-radiobuttonfor-to-get-a-list-of-radio-buttons-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!