Sometimes you have a field that is a look-up against a static group of ID/types that are either short enough to not be worth a whole separate table, or for organizational reasons don't make sense as a BelongsTo. For example, an article, page on a web-site, or blog post could have a statusID that indicates its stage in workflow. To work with something familiar let's modify Post from the BlogSample
to have multiple states.
The rest of the class is left out for brevity, check the sample if you like.
public class Post : ActiveRecordBase { private StatusType _status_type_id; public enum StatusType { Editing = 0, Published = 1, Archived = 2 } [Property("status_type_id")] public StatusType Status { get { return _status_type_id; } set { _status_type_id = value; } } }
Then you can use Post.Status like any other property, or like any other enum, for example, setting
Post.Status = Post.StatusType.Archived;
No more crappy hard-coded status values.
To take this a step further, now you want to build a dropdown list for the StatusType for your view easily:
public class NameValue { private string _name; private long _id; public NameValue(long id, string name) { this._id = id; this._name = name; } public long Id { get { return _id; } set { _id = value; } } public string Name { get { return _name; } set { _name = value; } } public override string ToString() { return this._name; } }
ArrayList list = new ArrayList(); foreach (object valueProperty in Enum.GetValues(typeof(StatusType))) { string nameProperty = Enum.GetName(typeof(StatusType), valueProperty); if (nameProperty == value.ToString()) { selected = Convert.ToInt64(valueProperty); } list.Add(new NameValue(Convert.ToInt64(valueProperty), nameProperty)); }
Now you have a list. You can used the HtmlHelper.CreateOptions(...) to create a dropdown list.
