0

I'm working on an intranet site, specifically on a Weekly Monitoring tool for employees. What I need is to fill a DropDownList with weeks, example week:

Week : From 12/10/15 to 18/10/15

I'm able to filter on another page but with years and month:

CalendarController c = new CalendarController();
ViewBag.ListYears = c.ListYears(iyear);
ViewBag.ListMonths = c.ListMonths(imonth);
ViewBag.ListDaysOfMonth = _service.ListDaysOfMonth(iyear.ToString(), imonth.ToString());

And use forms to save them.

How do I fill my DDList with a list of, let's say, all the weeks in 2015?

CDspace
  • 2,639
  • 18
  • 30
  • 36
Christopher
  • 1,712
  • 2
  • 21
  • 50

2 Answers2

1

To return a list of the formatted weeks, you could use the following method

public List<string> FetchWeeks(int year)
{
    List<string> weeks = new List<string>();
    DateTime startDate = new DateTime(year, 1, 1);
    startDate = startDate.AddDays(1 - (int)startDate.DayOfWeek);
    DateTime endDate = startDate.AddDays(6);
    while (startDate.Year < 1 + year)
    {
        weeks.Add(string.Format("Week: From {0:dd/MM/yyyy}to {1:dd/MM/yyyy}", startDate, endDate));
        startDate= startDate.AddDays(7);
        endDate = endDate.AddDays(7);
    }
    return weeks;
}

and then in the controller

var weeks = FetchWeeks(2105);
ViewBag.Weeks = new SelectList(weeks);

However this will post back the formatted value, which may not be of much use in the controller, so this could be modified so that you create IEnumerable<SelectListItem> where the Value property is a number representing the index of the week in the year and the Text property is the formatted text.

0

Here's how you get the week of the current year (kudos goes here):

var jan1 = new DateTime(DateTime.Today.Year , 1, 1);
//beware different cultures, see other answers
var startOfFirstWeek = jan1.AddDays(1 - (int)(jan1.DayOfWeek));
var weeks=
    Enumerable
        .Range(0,54)
        .Select(i => new {
            weekStart = startOfFirstWeek.AddDays(i * 7)
        })
        .TakeWhile(x => x.weekStart.Year <= jan1.Year)
        .Select(x => new {
            x.weekStart,
            weekFinish=x.weekStart.AddDays(4)
        })
        .SkipWhile(x => x.weekFinish < jan1.AddDays(1) )
        .Select((x,i) => new {
            x.weekStart,
            x.weekFinish,
            weekNum=i+1
        });

Then you add weeks to the dropdownList

Community
  • 1
  • 1
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142