我有一个简单的日历页面,我需要用可用日期列表填充它。
我得到的列表如下:
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事件?
答案 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;
}