12

(just learning MVC)

I have created a model class:

public class Employee
    {
        public int ID { get; set; }

        [Required(ErrorMessage="TM Number is Required")]
        public string tm_number { get; set; }

        //use enum?
        public tmRank tm_rank { get; set; }
    }

The model class refers to the enum 'tmRank':

public enum tmRank
    {
        Hourly, Salary
    }

When I create a view from this model the 'tm_rank' field does not appear? My hope was that MVC would create a list of the enum values.

1
  • What does your view look like right now? Are you using EditorFor() or something else? Commented Feb 3, 2011 at 20:31

1 Answer 1

14

My guess is it doesn't understand what type of field to create for an Enum. An Enum can be bound to a dropdown list, a set of radio buttons, a text box, etc.

What type of entry do you want for your Enum? Should they select it from a list? Answering that can help us with the code needed for that situation.

Edited to add code per your comment:

public static SelectList GetRankSelectList()
{

    var enumValues = Enum.GetValues(typeof(TmRank)).Cast<TmRank>().Select(e => new { Value = e.ToString(), Text = e.ToString() }).ToList();

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

Then in your model:

public class Employee
{
    public Employee() 
    { 
        TmRankList = GetRankSelectList();
    }

    public SelectList TmRankList { get; set; }
    public TmRank TmRank { get; set; }
}

And finally you can use it in your View with:

<%= Html.DropDownListFor(c => c.TmRank, Model.TmRankList) %>

This will hold the enum values in TmRankList. When your form is posted, TmRank will hold the selected value.

I wrote this without visual studio though, so there might be issues. But this is the general approach that I use to solve it.

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

4 Comments

You are correct - I was hoping to have the user select from a list.
Would there be a way to get the value for a label rather then a dropdown?
Yeah, you can omit the select lists, since there's really no concept of a list with a label. just do Html.LabelFor(c => c.Property)
One typo/error, I think it should be TmRankList = GetRankSelectList(). Otherwise works really well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.