0

I have many enums in my model and would like an automated way of generating radio buttons for them in my form rather than adding a @Html.RadiobuttonFor for each value. For example, I have the following enum:

public enum Gender
{
    Male = 1,
    Female = 2
}
Ali Almohsen
  • 1,311
  • 3
  • 13
  • 24
  • 1
    Create a `HtmlHelper` extension method –  Dec 12 '17 at 09:04
  • 1
    Refer [this answer](https://stackoverflow.com/questions/27984973/enum-radiobuttonfor-editor-template-set-value/27995314#27995314) for an example –  Dec 12 '17 at 09:06
  • @StephenMuecke Why downvote the question if you didn't like the answer? Anyways, really liked your suggestion and decided to adopt a good chunk of it to improve my answer. Thanks for the advice! – Ali Almohsen Dec 12 '17 at 11:46
  • The question was down voted because its off-topic. It's just a _gimme the code_ question. It shows no effort, includes no attempt etc. Its clear you wanted to add a self answer, but that does mean you can ask off-topic questions. –  Dec 13 '17 at 02:14
  • If you want to add canonical question/answer then read [this meta post](https://meta.stackoverflow.com/questions/291992/what-is-a-canonical-question-answer-and-what-is-their-purpose), and for an example of a couple I have created refer [here](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) and [here](https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-of-type-but-this-dictionary-requ). Note also that they are typically made Community Wiki answers. –  Dec 13 '17 at 02:15
  • But before your create one, I suggest you gain a lot more knowledge in the subject (your initial answer was awful code and showed no understanding of asp.net-mvc) –  Dec 13 '17 at 02:18

1 Answers1

1

Create the following helper class:

using System.Linq.Expressions;
using System.Text;

namespace System.Web.Mvc.Html
{
    public static class EnumHelpers
    {
        public static MvcHtmlString EnumRadioButtonListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, ListDirection listDirection)
        {
            ModelMetadata metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
            string enumName = ExpressionHelper.GetExpressionText(expression);
            if (!metaData.ModelType.IsEnum)
                throw new ArgumentException(string.Format("The property {0} is not an enum", enumName));

            var html = new StringBuilder();

            string name = ExpressionHelper.GetExpressionText(expression);
            string[] names = Enum.GetNames(metaData.ModelType);
            foreach (string value in names)
            {
                string id = string.Format("{0}_{1}", name, value);
                html.Append(String.Format("<label class=\"{1}\" for=\"{0}\">",
                    new string[] {
                                    id,
                                    listDirection == ListDirection.Horizontal ? "radio-inline" : "radio"
                            }));
                html.Append(helper.RadioButtonFor(expression, value, new { id = id }));
                html.Append(String.Format(" {0}</label>", value));
            }

            return MvcHtmlString.Create(html.ToString());
        }

        public enum ListDirection
        {
            Vertical,
            Horizontal
        }
    }
}

Then call it in Razor view:

@Html.EnumRadioButtonListFor(model => model.PaymentMethod, EnumHelpers.ListDirection.Horizontal)
Ali Almohsen
  • 1,311
  • 3
  • 13
  • 24
  • 1
    No strong typed model binding. No client side validation. Only works if the name of the property is exactly the same as the name of the `enum`. Will not select the correct radio button based on the value of the property, and will loose the selected value is the view is returned. etc etc. etc –  Dec 12 '17 at 09:09
  • @StephenMuecke made several improvements based on your recommendation, many based on [your answer](https://stackoverflow.com/questions/27984973/enum-radiobuttonfor-editor-template-set-value/27995314#27995314). – Ali Almohsen Dec 12 '17 at 11:50