开发者

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

(just learning MVC)

I have created a model class:

public class Employee
    {
        public int ID开发者_如何学C { 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜