ASP .NET MVC - Using a enum as part of the model

2020-05-23 11:23发布

问题:

(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:

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.