Czasami przy wyświetlaniu kalendarza należy uniemożliwić wyświetlanie dni weekendowych i weekendowych w nagłówku dnia, czy jest jakiś sposób, aby to zrobić, korzystając z numeru ASP.NET Calendar control?Jak ukryć weekendy podczas korzystania z kontrolki ASP.NET Calendar?
Odpowiedz
Ponieważ sterowanie jest zapewnione, nie można tego zrobić bez zmiany sterowania. Jednym ze sposobów na to jest zastąpienie metod, aby usunąć informacje z wyjścia przed wysłaniem go z powrotem do klienta.
Poniżej znajduje się zrzut ekranu z czym kontrola wygląda przy wytapianiu:
Poniżej przedstawiono podstawowe przesłanianie kontrola wykaże, że usuwając dziennie kolumny weekendowe z kontrolą.
/*------------------------------------------------------------------------------
* Author - Rob (http://stackoverflow.com/users/1185/rob)
* -----------------------------------------------------------------------------
* Notes
* - This might not be the best way of doing things, so you should test it
* before using it in production code.
* - This control was inspired by Mike Ellison's article on The Code Project
* found here: http://www.codeproject.com/aspnet/MellDataCalendar.asp
* ---------------------------------------------------------------------------*/
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Xml;
namespace DataControls
{
/// <summary>
/// Example of a ASP.NET Calendar control that has been overriden to force
/// the weekend columns to be hidden on demand.
/// </summary>
public class DataCalendar : Calendar
{
private bool _hideWeekend;
private int _saturday;
private int _sunday;
/// <summary>Constructor</summary>
public DataCalendar()
: base()
{
// Default to showing the weekend
this._hideWeekend = false;
// Set the default values for Saturday and Sunday
this.Saturday = 6;
this.Sunday = 0;
}
/// <summary>
/// Indicate if the weekend days should be shown or not, set to true
/// if the weekend should be hidden, false otherwise. This field
/// defaults to false.
/// </summary>
public bool HideWeekend
{
get { return this._hideWeekend; }
set { this._hideWeekend = value; }
}
/// <summary>
/// Override the default index for Saturdays.
/// </summary>
/// <remarks>This option is provided for internationalization options.</remarks>
public int Saturday
{
get { return this._saturday; }
set { this._saturday = value; }
}
/// <summary>
/// Override the default index for Sundays.
/// </summary>
/// <remarks>This option is provided for internationalization options.</remarks>
public int Sunday
{
get { return this._sunday; }
set { this._sunday = value; }
}
/// <summary>
/// Render the day on the calendar with the information provided.
/// </summary>
/// <param name="cell">The cell in the table.</param>
/// <param name="day">The calendar day information</param>
protected override void OnDayRender(TableCell cell, CalendarDay day)
{
// If this is a weekend day and they should be hidden, remove
// them from the output
if (day.IsWeekend && this._hideWeekend)
{
day = null;
cell.Visible = false;
cell.Text = string.Empty;
}
// Call the base render method too
base.OnDayRender(cell, day);
}
/// <summary>
/// Render the calendar to the HTML stream provided.
/// </summary>
/// <param name="html">The output control stream to write to.</param>
protected override void Render(HtmlTextWriter html)
{
// Setup a new HtmlTextWriter that the base class will use to render
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter calendar = new HtmlTextWriter(sw);
// Call the base Calendar's Render method allowing OnDayRender()
// to be executed.
base.Render(calendar);
// Check to see if we need to remove the weekends from the header,
// if we do, then remove the fields and use the new verison for
// the output. Otherwise, just use what was previously generated.
if (this._hideWeekend && this.ShowDayHeader)
{
// Load the XHTML to a XML document for processing
XmlDocument xml = new XmlDocument();
xml.Load(new StringReader(sw.ToString()));
// The Calendar control renders as a table, so navigate to the
// second TR which has the day headers.
XmlElement root = xml.DocumentElement;
XmlNode oldNode = root.SelectNodes("/table/tr")[1];
XmlNode sundayNode = oldNode.ChildNodes[this.Sunday];
XmlNode saturdayNode = oldNode.ChildNodes[this.Saturday];
XmlNode newNode = oldNode;
newNode.RemoveChild(sundayNode);
newNode.RemoveChild(saturdayNode);
root.ReplaceChild(oldNode, newNode);
// Replace the buffer
html.WriteLine(root.OuterXml);
}
else
{
html.WriteLine(sw.ToString());
}
}
}
}
O ile wiem, nie możesz, ale możesz eksperymentować z WeekendDayStyle, na przykład ustawiając styl z wyświetlaczem: brak. Alternatywnie możesz utworzyć niestandardowy formant odziedziczony po Kalendarzu i zastąpić Eter Render, OnDayRender lub coś innego.
Uważam, że można obsłużyć zdarzenie Dnia Renderowania i ukryć komórkę lub przypisać właściwości CSS, aby stała się niewidoczna lub wyszarzona. Poniżej znajduje się prosty przykład, mam nadzieję, że to pomaga.
protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
{
e.Cell.Visible = False;
// or
// e.Cell.Attributes.Add("class", "Invisible");
// or
// e.Cell.Attributes.Add("style", "display: none");
}
To właśnie ukrywa zawartość pola dzień, to trzeba jeszcze wykonać dodatkową pracę, aby móc usunąć dni nagłówek. – rjzii
Jeśli są OK, z użyciem roztworu jQuery, to trwa tylko kilka linijek kodu:
<script type="text/javascript">
$(document).ready(function() {
$('._title').parent().attr('colspan', '5'); // title row initially has a colspan of seven
$('._dayheader:first, ._dayheader:last', $('#<%= Calendar1.ClientID %>')).hide(); // remove first and last cells from day header row
$('._weekendday').hide(); // remove all the cells marked weekends
});
</script>
<asp:Calendar runat="server" ID="Calendar1">
<TitleStyle CssClass="_title" />
<DayHeaderStyle CssClass="_dayheader" />
<WeekendDayStyle CssClass="_weekendday" />
</asp:Calendar>
Oto kilka uwag z tym podejściem:
- Jeśli JavaScript jest wyłączony , klient zobaczy weekendy.
- W starszych, wolniejszych przeglądarkach rodzaj kalendarza przeskakuje podczas wykonywania jQuery podczas ładowania.
- To rozwiązanie może prawdopodobnie zostać zaimplementowane w prostym CSS z :first-child.
- Po dodaniu do strony kolejnego kalendarza należy zduplikować środkową linię kodu JavaScript. Jest to konieczne, ponieważ używamy: pierwszy i ostatni.
- Jeśli masz tylko kontrolę jednego kalendarza na stronie można uprościć środkową linię JavaScript usuwając drugi argument selektor jQuery:
$('#<%= Calendar1.ClientID %>')
Jak zacharydl sugerują, udało mi się ukryć weekendy przy użyciu jQuery. Wprowadziłem niewielką zmianę do oryginalnego kodu.
<script type="text/javascript">
HideWeekEnd();
function HideWeekEnd()
{
$('._title').parent().attr('colspan', '7');
$('._dayheader:nth-last-child(1) , ._dayheader:nth-last-child(2) ', $('#<%= Calendar1.ClientID %>')).hide(); // remove last two cells from day header row
$('._weekendday').hide(); // remove all the cells marked weekends
}
Sys.Application.add_init(appl_init);
function appl_init() {
var pgRegMgr = Sys.WebForms.PageRequestManager.getInstance();
pgRegMgr.add_endRequest(HideWeekEnd);
}
</script>
Będziesz musiał zarejestrować HideWeekEnd() na stronie endRequest, aby upewnić się, że zostanie wywołany podczas odsłania strony.
tutaj jest inny sposób za pomocą CSS tylko do osiągnięcia tego celu:
<style> .hidden, #Calendrier tr > th[abbr=Saturday], #Calendrier tr > th[abbr=Sunday] { display:none; } #Calendrier tr > th { text-align: center; } </style> <asp:Calendar ID="Calendar1" DayNameFormat="Full" runat="server" WeekendDayStyle-CssClass="hidden" ClientIDMode="Static" > </asp:Calendar>
Tylko niewielki komentarz, że kiedy to zaimplementowałem, nagłówki dni trwały od wtorku do soboty. Sztuczka polegała na zmianie linii: XmlNode sundayNode = oldNode.ChildNodes [0]; do: XmlNode sundayNode = oldNode.ChildNodes [5]; Możliwe, że jestem w Wielkiej Brytanii? – Brian
@Brian - Najprawdopodobniej tak się stało, jestem w Stanach Zjednoczonych, gdzie w kalendarzu wykorzystano niedzielę jako pierwszy dzień tygodnia. Nie uwzględniłem niczego w logice lokalizacji w kodzie, więc może to być w pewnym momencie coś do zrobienia. – rjzii
@Joel - Po prostu zaimplementowałem to i przetestowałem w IE, w sposób przewidywalny nie wygląda to tak, jak można by oczekiwać. Komórki nagłówków i dni z dnia tygodnia renderują się na poziomie 5/7 szerokości kalendarza. Wynika to z dwóch kolumn, które zostały usunięte. Mam na to poprawkę (zamień dowolną "szerokość: 14%" w xml na "szerokość: 20%") i chciałbym udostępnić moje rozwiązanie innym. Jaki jest najlepszy sposób, żeby o tym porozmawiać? – Brian