0

我有一个简单的日历页面,我需要用可用日期列表填充它。

我得到的列表如下:

 List<DateTime> availableDates = (from d in sb.GetDaysWithAvailableSlotsByLocation(3)
                                         select d.Date).ToList<DateTime>();

但是,看起来日历在 Page_load 中调用此函数之前呈现,因为我需要将此查询放入我的代码中两次以使其工作:

    public partial class BookYourSlot : System.Web.UI.Page
{

    public SlotBooker sb = new SlotBooker();
    public List<DateTime> availableDates = new List<DateTime>();

    protected void Page_Load(object sender, EventArgs e)
    {

        List<DateTime> availableDates = (from d in sb.GetDaysWithAvailableSlotsByLocation(3)
                                         select d.Date).ToList<DateTime>();
        DateTime firstAvailable = availableDates.Min();

        calSlotBooker.VisibleDate = firstAvailable;



    } 


    protected void calSlotBooker_DayRender(object sender, DayRenderEventArgs e)
    {
       List<DateTime> availableDates = (from d in sb.GetDaysWithAvailableSlotsByLocation(3)
                                        select d.Date).ToList<DateTime>();


        if (!(availableDates.Contains(e.Day.Date)) || (e.Day.Date.DayOfWeek == DayOfWeek.Saturday) || (e.Day.Date.DayOfWeek == DayOfWeek.Sunday))
        {
            e.Cell.BackColor = System.Drawing.Color.Silver;
            e.Day.IsSelectable = false;
            e.Cell.ToolTip = "Unavailable";
        }

    }
}

这似乎非常低效,因为每次呈现单元格时它都会调用 availableDates 查询。

如何在页面上执行一次,并使其可供日历控件的 DayRender 事件访问?

4

2 回答 2

0

将列表存储为页面属性:

List<DateTime> AvailableDates {get; set;}

protected void Page_Load(object sender, EventArgs e)
{
    AvailableDates = (from d in sb.GetDaysWithAvailableSlotsByLocation(3)
                                     select d.Date).ToList<DateTime>();
    DateTime firstAvailable = AvailableDates.Min();
    calSlotBooker.VisibleDate = firstAvailable;
} 

protected void calSlotBooker_DayRender(object sender, DayRenderEventArgs e)
{
    if (!(AvailableDates.Contains(e.Day.Date)) || (e.Day.Date.DayOfWeek == DayOfWeek.Saturday) || (e.Day.Date.DayOfWeek == DayOfWeek.Sunday))
    {
        e.Cell.BackColor = System.Drawing.Color.Silver;
        e.Day.IsSelectable = false;
        e.Cell.ToolTip = "Unavailable";
    }
}

看起来日历在 Page_load 中调用此函数之前呈现

我不信。渲染发生在加载之后,所以除非这个特定的控件做了一些奇怪的事情(比如 Render after Initbut before Load) ,Load否则应该首先调用。

我的猜测是你试图从方法中访问一个局部变量,这是行不通的,但不是因为事件的顺序。Page_LoadRender

于 2013-06-27T14:58:07.200 回答
0

发生的情况是,您隐藏了availableDates. 在Page_Load您使用的不是在 on 上声明的字段Page,而是在方法范围内本地声明的字段(在 中也是如此calSlotBooker_DayRender)。只需将变量的局部声明更改List<DateTime> availableDatesavailableDates.

public List<DateTime> availableDates;

protected void Page_Load(object sender, EventArgs e)
{
    availableDates = (from d in sb.GetDaysWithAvailableSlotsByLocation(3)
                                     select d.Date).ToList<DateTime>();
    DateTime firstAvailable = availableDates.Min();
    calSlotBooker.VisibleDate = firstAvailable;
} 
于 2013-06-27T15:18:56.977 回答