1

allSundaysInMonthのViewModel、私はこれを同じに保ちました:

  namespace TradeUK.Admin.Web.ViewModels
  {
      public class SundaysInMonthViewModel
      {
         public IEnumerable<SelectListItem> AllSundays { set; get; }
         public string SelectedSunday { set; get; }
      }
  }

次に、私のアクションで新しいコード:

public ActionResult TradeUKKPISearchesData() //show dropdownlist in the view
{
  var now = DateTime.Now;
  var lastMonth = now.AddMonths(-1);
  var lastMonthSundays = GetDatesOfSundays(lastMonth.Year, lastMonth.Month);
  var thisMonthSundays = GetDatesOfSundays(now.Year, now.Month);
  var sundaysToTakeFromLastMonth = 2;
  var sundays = lastMonthSundays.Skip(Math.Max(0, lastMonthSundays.Count() - sundaysToTakeFromLastMonth)).Take(sundaysToTakeFromLastMonth).Concat(thisMonthSundays);

  var allSundaysInThisMonth = new SundaysInMonthViewModel
  {
    AllSundays = sundays.Select(x => new SelectListItem
    {
      Value = x.ToString("dd-MM-yyyy"),
      Text = x.ToString("dd-MM-yyyy"),
    });

    //or must I have the code here? not sure how all this works yet
    SelectedSunday = sundays.Select(y => new SelectListItem
    {
      Value = 
      Text = 
    }) 
  };

  //this is what I meant or can I add this to the above?
  var selectedSunday = new SundaysInMonthViewModel{
    SelectedSunday = sundays.Select(y => new SelectListItem
    {
      Value = 
    })
  }
  return View(allSundaysInThisMonth);
}

ありがとう

4

1 に答える 1

0
public IEnumerable<DateTime> GetDatesOfSundays(int year, int month)
{
    var ci = CultureInfo.InvariantCulture;
    for (int i = 1; i <= ci.Calendar.GetDaysInMonth(year, month); i++)
    {
        var date = new DateTime(year, month, i);
        if (date.DayOfWeek == DayOfWeek.Sunday)
        {
            yield return date;
        }
    }
}

そして、コントローラーで:

public ActionResult TradeUKKPISearchesData()
{
    var now = DateTime.Now;
    var lastMonth = now.AddMonths(-1);
    var lastMonthSundays = GetDatesOfSundays(lastMonth.Year, lastMonth.Month);
    var thisMonthSundays = GetDatesOfSundays(now.Year, now.Month);
    var sundaysToTakeFromLastMonth = 2;
    var sundays = lastMonthSundays
        .Skip(Math.Max(0, lastMonthSundays.Count() - sundaysToTakeFromLastMonth))
        .Take(sundaysToTakeFromLastMonth)
        .Concat(thisMonthSundays);

    var allSundaysInThisMonth = new SundaysInMonthViewModel
    {
        AllSundays = sundays.Select(x => new SelectListItem
        {
            // TODO: Adjust the formats you want for the 
            // Value and Text of your ddl
            Value = x.ToString("yyyy-MM-dd"),
            Text = x.ToString("yyyy-MM-dd"),
        }),
        SelectedSunday = thisMonthSundays
            .Where(x => x < now)
            .Last()
            .ToString("yyyy-MM-dd")
    };
    return View(allSundaysInThisMonth);
}

そしてあなたの見解では:

@model SundaysInMonthViewModel
...
@Html.DropDownListFor(x => x.SelectedSunday, Model.AllSundays)
于 2012-08-15T07:44:18.687 に答える