Marky68
Marky68

Reputation: 95

how do you fill programmatically a selector using an enum with MVC in the view page with razor

I want to fill a selector using an enumerator. I want to do this operation in theView page with razor/VB or C#

Upvotes: 0

Views: 666

Answers (2)

Anil Vangari
Anil Vangari

Reputation: 570

If you have an enum something like below then you may prefer to split the names at capital letters.

public enum Gender
{
    NotSpecified = 0,
    Male,
    Female
}

Here is the code to split and return the SelectList to show the enums in the UI but get the selected value back as enum in model.

Splitting logic is from one of the SO post. Thanks to the poster.

public class EnumHelper
{
    public static SelectList GetSelectList<T>()
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
            throw new ArgumentException("The specified type is not enum");

        List<SelectListItem> items = new List<SelectListItem>();

        var values = Enum.GetValues(enumType);

        foreach (var value in values)
        {
            items.Add(new SelectListItem()
            {
                Value = value.ToString(),

                // Split at capital letters
                Text = Regex.Replace(Enum.GetName(enumType, value), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")
            });
        }

        return new SelectList(items, "Value", "Text");
    }

A sample usage in razor is below

<div class="editor-label">
    @Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Gender, EnumHelper.GetSelectList<Gender>())
    @Html.ValidationMessageFor(model => model.Gender)
</div>

HTH

Upvotes: 1

Anil Vangari
Anil Vangari

Reputation: 570

For simple enum names the following code should work.

In Razor/C#

<tr>
    <th>
        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
    </th>
    <td>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(Gender))))
            @Html.ValidationMessageFor(model => model.Gender)
        </div>
    </td>
</tr>

My enum is simple one like this

public enum Gender
{
    Male,
    Female
}

Upvotes: 0

Related Questions