DropDownList containing weeks

我怕爱的太早我们不能终老 提交于 2021-02-11 17:29:47

问题


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?


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/33100782/dropdownlist-containing-weeks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!