Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a best practice way to define select/dropdown options for view creation or db store

I'm still not yet sure on the best way to store selectlist options for front end display or db storage.

I've been using Enums at the moment, and also using description decorators (How do you create a dropdownlist from an enum in ASP.NET MVC?)

I'm now thinking that I might as well just create a full class for this stuff, so I can store the following information properly with full control:

  1. Item Name
  2. Full description
  3. int for storage in db
  4. order
  5. Any methods to get information in anyway from the list.

Is it right I should be thinking about implementing all this myself by hand? I want a really solid way of doing this, and an enum doesn't really feel like it's going to cut it.

like image 354
Chris Barry Avatar asked Mar 13 '12 12:03

Chris Barry


People also ask

How do I save a dropdown selected value in a database?

Columns["Id"]. ToString(); ", basically binding "Id" column values as dropdown values. Once you will select dropdown value and enter text values in it, it will save data in database.


1 Answers

Is it right I should be thinking about implementing all this myself by hand?

Yes. Enums are often leaky and insufficient abstractions that aren't always suitable for the complex domain model you actually wish to represent.

Rather than roll your own, you may want to consider Headspring's Enumeration class (via github, nuget). We use it all the time instead of enums because it's nearly as simple and is much more flexible.

An example of a "State" enumeration and using it as a select list:

public class State : Enumeration<State>
{
    public static State Alabama = new State(1, "AL", "Alabama");
    public static State Alaska = new State(2, "AK", "Alaska");
    // .. many more
    public static State Wyoming = new State(3, "WY", "Wyoming");

    public State(int value, string displayName, string description) : base(value, displayName)
    {
        Description = description;
    }

    public string Description { get; private set; }
}

public IEnumerable<SelectListItem> Creating_a_select_list(State selected)
{
    return State.GetAll().Select(
        x => new SelectListItem
        {
            Selected = x == selected,
            Text = x.Description,
            Value = x.Value.ToString()
        });
}

I'm not trying to sell you on this particular implementation, you could certainly hand code your own (the Enumeration class is only about 100 lines of code). But I definitely think you'd benefit from moving beyond basic enums. It is the right approach given the scenario you described in your question.

like image 58
Kurt Schindler Avatar answered Sep 29 '22 15:09

Kurt Schindler