我应该在哪里放置此查询以避免多次运行它?

时间:2013-06-27 14:55:02

标签: c# linq

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

我得到的列表如下:

 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事件?

2 个答案:

答案 0 :(得分: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

中调用此函数之前,它看起来像是日历渲染

我对此表示怀疑。渲染在加载后发生,因此除非此特定控件执行奇怪的操作(例如Init之后但Load之前的渲染)Load应首先调用。

我的猜测是您尝试从Page_Load方法访问Render本地变量,这不起作用,但不是因为事件的顺序。

答案 1 :(得分:0)

您所隐藏的availableDates声明会发生什么。在Page_Load中,您没有使用在Page上声明的字段,而是在方法范围内本地声明的字段(同样在calSlotBooker_DayRender中)。只需将变量List<DateTime> availableDates的本地声明更改为availableDates

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;
}