Gavin5511
Gavin5511

Reputation: 791

How do I create a reusable dropdown list

I'm after creating a really simple drop-down list, which essentially shows various times, and their value is the minutes past midnight for each time. For example:

Value       Time
60          01:00 AM
75          01:15 PM
90          01:30 PM
105         01:45 PM
120         02:00 PM

etc

The thing is, I need to use the same drop-down list in a whole bunch of views and controllers in my application. After reading a couple of articles, it seems like I need to create a static class for this? But all the examples seem to be way more complicated than I actually need. Is it an IList that I should be creating for this?

Upvotes: 0

Views: 502

Answers (2)

Trung Duong
Trung Duong

Reputation: 3475

You could try the following method

  1. Create a static class that generate data source for the dropdown
public static class DropdownData
{
    public static IList<SelectListItem> GetTimeList(string defaultValue)
    {
        var times = new List<SelectListItem>();
        times = Enumerable.Range(4, 4).Select(x => {
            var minute = x * 15;
            var time = DateTime.Today.AddMinutes(minute);
            return new SelectListItem()
            {
                Value = minute.ToString(),
                Text = time.ToString("hh:mm tt"),
                Selected = (!string.IsNullOrEmpty(defaultValue) && minute.Equal(defaultValue))
            };
        }).ToList();
        return times;
    }
}
  1. In your views, you could create dropdown list with data source that generated in step 1
@Html.DropDownList("TimeList", DropdownData.GetTimeList("75"), new { @class = "form-control" })

Upvotes: 1

CDove
CDove

Reputation: 1950

If you need a value to be Global, then yes, you'll want it to be public static in C#. I recommend also putting it in a public static class so you can access it by name.

public static class MyData
{
     public static IEnumerable<DateTime> ValueTimes { get; set;} //(or IList or List<T> or whatever you want)     
}

public class IDoStuff
{
  public DateTime myTime { get; set; }
  public IDoStuff(DateTime d) //constructor
  {
     if(ValueTimes.IndexOf(d) != -1) //-1 says I no findie
        myTime = d;
     else
        throw new ApplicationException("That's not a valid time, dummy");
  }
}

See, easy peasy. Also, use DateTime or TimeSpan, even if it's all in the same day. Don't use strings to represent time, you're asking for trouble that way.

Edit: While I was putting up the solution, you posted sample data. Given this:

Value       Time
60          01:00 AM
75          01:15 PM
90          01:30 PM
105         01:45 PM
120         02:00 PM

I think you can actually just do this and skip the static variable:

public static Timespan GetTime(int value)
{
   return Timespan.FromMinutes(value);

}

Upvotes: 0

Related Questions