1

How to create a dropdown list using enum value in mvc4

I have a class Language.cs

 public enum Language {
    English = 0
}

And my property is

public Language Language { get; set; }

How will i call in my view through a dropdown list

2

2 Answers 2

6

You could have a view model:

public class MyViewModel
{
    public Language SelectedLanguage { get; set; }
    public IEnumerable<SelectListItem> Languages
    {
        get 
        {
            var languages = 
                from l in Enum.GetValues(typeof(Language))
                select new { ID = (int)d, Name = d.ToString() };
            return new SelectList(languages , "ID", "Name", this.SelectedLanguage);
        }
    }
}

and then in your view:

@Html.DropDownListFor(x => x.SelectedLanguage, Model.Languages)

Another possibility is to write a custom helper that will encapsulate this logic as shown in this blog post.

Sign up to request clarification or add additional context in comments.

Comments

2

This will do the job:

public enum Language
{
    English,
    French,
    Spanish
}

public static class Enum
{
    public static IEnumerable<T> GetItems<T>()
    {
        return System.Enum.GetValues(typeof(T)).Cast<T>();
    }
}

public class ViewModel
{
    public Language Language
    {
        get;
        set;
    }

    public IEnumerable<SelectListItem> Languages
    {
        get
        {
            return Enum.GetItems<Language>().Select(x => new SelectListItem() { Text = x.ToString(), Value = x.ToString() });
        }
    }
}

Html:

@model ViewModel
@Html.DropDownListFor(a => a.Language, Model.Languages)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.