0

I have an .aspx web form. When Ajax Calendar is changed, I'm not being able to capture date since there is no Selection_changed event firing. I tried to fire one, but that is also not working. Not sure if I should change the calendar control.

This is the markup:

<body> <form id="form1" runat="server"> <!-- Required for UpdatePanel and CalendarExtender --> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true" /> <div class="container mt-4"> <div class="card"> <div class="card-header bg-primary text-white"> Report Selection </div> <div class="card-body"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <table class="table table-borderless mb-0"> <tr> <td> <label for="txtDate">Select Date:</label> <asp:TextBox ID="txtDate" runat="server" CssClass="form-control" /> <ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="txtDate" Format="MM/dd/yyyy" CssClass="calendarStyle" /> </td> <td> <label for="DDLDepartment">Select Department:</label> <asp:DropDownList ID="DDLDepartment" runat="server" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="DDLDepartment_SelectedIndexChanged"> <asp:ListItem Text="-- Select --" Value="" /> <asp:ListItem Text="HR" Value="HR" /> <asp:ListItem Text="IT" Value="IT" /> </asp:DropDownList> </td> </tr> <table id="tblReportList" cellpadding="5" cellspacing="0" width="100%"> <tr> <td> <asp:DataList ID="DLReports" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" CssClass="table table-striped"> <ItemTemplate> <img border="0" src='<%# GetMyImage(Eval("File_Extension").ToString()) %>' /> &nbsp; <a onclick='LogAttempt("<%# Eval("Display_Name") %>");' href='<%# ReturnUrl(Eval( "UNC_Path").ToString(), Eval( "File_Name").ToString(), Eval("File_Extension").ToString(), "" + Eval("Frequency").ToString())%>' target="_blank" class='tblSOP'><%# Eval("Display_Name").ToString() %> </a>&nbsp;&nbsp; </ItemTemplate> </asp:DataList> </td> </tr> </table> </table> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID="DDLDepartment" EventName="SelectedIndexChanged" /> </Triggers> </asp:UpdatePanel> <asp:Panel ID="Panel2" runat="server"> <div class="coverGrey"></div> </asp:Panel> </div> </div> </div> </form> </body> 

Here is the C# code:

namespace Reports_NH { public partial class Reports_NH : System.Web.UI.Page { protected System.Data.DataSet DT; [System.Web.Services.WebMethod()] public static void Log_For_Site_Tracking(string MyUrl) { SqlConnection SqlCon = new SqlConnection(App_Tools.Get_App_Sql_Connection()); SqlCommand SqlCmd = SqlCon.CreateCommand(); try { SqlCon.Open(); SqlCmd.CommandText = "insert into MATCHDB.REPORTDATA.Site_Tracking values ('" + DateTime.Now.ToString() + "', 'AdHoc Report: " + MyUrl + "','" + System.Web.HttpContext.Current.User.Identity.Name.ToString().ToUpper() + "', '')"; SqlCmd.ExecuteNonQuery(); } catch (Exception ex) { } finally { SqlCon.Close(); SqlCmd = null/* TODO Change to default(_) if this is not a reference type */; SqlCon = null/* TODO Change to default(_) if this is not a reference type */; } } public enum UserType { Restricted = 1, NonRestricted = 2 } protected UserType GetUserType(ref System.Data.SqlClient.SqlCommand CommandObj) { bool IsRestricted; IsRestricted = false; CommandObj.CommandText = "select SOEID from CFMCAPP.Restricted_Users "; System.Data.SqlClient.SqlDataReader DR; DR = CommandObj.ExecuteReader(); while (DR.Read()) { if (System.Web.HttpContext.Current.User.Identity.Name.ToString().ToUpper().Contains(DR[0].ToString().ToUpper())) { IsRestricted = true; } } DR.Close(); if (IsRestricted == true) return UserType.Restricted; else return UserType.NonRestricted; } protected void Page_Load(object sender, EventArgs e) { DT = new System.Data.DataSet(); string connString = App_Tools.Get_App_Sql_Connection(); SqlConnection SqlCon = new SqlConnection(connString); string UserTypeCriteria = ""; SqlCon.Open(); SqlCommand SqlCmd = SqlCon.CreateCommand(); SqlDataAdapter SqlAdp = new SqlDataAdapter(SqlCmd); //testing // var identity = User.Identity; // Response.Write("<br/>User Identity:" + identity.Name + "<br/>"); // Response.Write("<br/>User Authentication Type:" + identity.AuthenticationType + "<br/>"); // Response.Write("<br/>User IsAuthenticated:" + identity.IsAuthenticated + "<br/>"); // One Main report access split code. Get user access rights and provide access to Adhocs based on this. UserType MyUser; MyUser = GetUserType(ref SqlCmd); switch (MyUser) { case UserType.Restricted: { UserTypeCriteria = " and ((Restricted_Detail is null) or (Restricted_Detail = 0))"; break; } default: { UserTypeCriteria = " and 2=2"; break; } } // DDLDepartment Fill on First Load if (!IsPostBack) { // Panel2.Style.Item["display"] = "none"; Panel2.Visible = false; // fill in selectable departments SqlCmd.CommandText = "SELECT DISTINCT Department FROM MATCHDB.CFMCAPP.Define_External_Reports_New where Automize_Task_Name <> 'EMEA'" + UserTypeCriteria; SqlAdp.Fill(DT, "Departments"); this.DDLDepartment.DataSource = DT; this.DDLDepartment.DataMember = "Departments"; this.DDLDepartment.DataTextField = "Department"; this.DDLDepartment.DataBind(); this.DDLDepartment.Items.Add("[View All]"); this.txtDate.Text = DateTime.Now.ToString("MM/dd/yyyy"); // Get Cookies, set value HttpCookie CookE = Request.Cookies["Reports_Page_Group"]; //DDLDepartment.SelectedIndexChanged += DDLDepartment_SelectedIndexChanged; //DDLDepartment.AutoPostBack = true; if (!(CookE == null)) { if (!(CookE["Selected_Group"] == null)) { if (this.DDLDepartment.Items.Contains(new System.Web.UI.WebControls.ListItem(CookE["Selected_Group"]))) this.DDLDepartment.SelectedValue = CookE["Selected_Group"]; else this.DDLDepartment.Items[0].Selected = true; } else this.DDLDepartment.Items[0].Selected = true; } else // Me.DDLDepartment.Items(0).Selected = True this.DDLDepartment.SelectedValue = "[View All]"; } else //this.Panel2.Style.Item("display") = "block"; Panel2.Visible = true; // Fill in Reports List, the postback urls will redirect to report page if (this.DDLDepartment.Text != "[View All]") SqlCmd.CommandText = "SELECT * FROM MATCHDB.CFMCAPP.Define_External_Reports_New Where Department = '" + this.DDLDepartment.Text + "'" + UserTypeCriteria + " and Automize_Task_Name <> 'EMEA' order by Display_Name asc"; else SqlCmd.CommandText = "SELECT * FROM MATCHDB.CFMCAPP.Define_External_Reports_New Where 1=1 " + UserTypeCriteria + " and Automize_Task_Name <> 'EMEA' order by Display_Name asc"; SqlAdp.Fill(DT, "Reports"); DataTable DTReports = DT.Tables["Reports"]; ParseDataTable(ref DTReports); DLReports.DataSource = DT; this.DLReports.DataMember = "Reports"; DLReports.DataBind(); // cleanUp SqlCon.Close(); SqlCmd = null/* TODO Change to default(_) if this is not a reference type */; SqlAdp = null/* TODO Change to default(_) if this is not a reference type */; SqlCon = null/* TODO Change to default(_) if this is not a reference type */; } protected void ParseDataTable(ref System.Data.DataTable DT) { DateTime SelectedDate = System.Convert.ToDateTime(txtDate.Text); string The_Montha_Date = SelectedDate.ToString("MMyy");//Format(SelectedDate, "MMyy"); // 0625 string The_Date = SelectedDate.ToString("MMddyy"); //Strings.Format(SelectedDate, "MMddyy"); List<System.Data.DataRow> RowsToDelete = new List<System.Data.DataRow>(); string LocalPath = ConfigurationManager.AppSettings["LocalReportPath"]; //App_Tools.Get_LocalReportPath; string RemotePath = ConfigurationManager.AppSettings["RemoteReportPath"]; //App_Tools.Get_RemoteReportPath; if (RemotePath.ToUpper() != "NONE") { // Get list of rows to delete foreach (System.Data.DataRow dr in DT.Rows) { if (dr["Frequency"].GetType() == typeof(System.DBNull)) { if (!(System.IO.File.Exists(dr["UNC_Path"].ToString().Replace(RemotePath, LocalPath) + @"\" + dr["File_Name"] + The_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } else if (dr["Frequency"].ToString() == "ASP Page") { } else if (dr["Frequency"].ToString() == "MTD") { //MTD are downloaded directly if (!(System.IO.File.Exists(dr["UNC_Path"].ToString().Replace(RemotePath, LocalPath) + @"\" + dr["File_Name"] + The_Montha_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } else if (!(System.IO.File.Exists(dr["UNC_Path"].ToString().Replace(RemotePath, LocalPath) + @"\" + dr["File_Name"] + The_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } } else // Get list of rows to delete foreach (System.Data.DataRow dr in DT.Rows) { if (dr["Frequency"].GetType() == typeof(System.DBNull)) { if (!(System.IO.File.Exists(dr["UNC_Path"] + @"\" + dr["File_Name"] + The_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } else if (dr["Frequency"].ToString() == "ASP Page") { } else if (dr["Frequency"].ToString() == "MTD") { if (!(System.IO.File.Exists(dr["UNC_Path"] + @"\" + dr["File_Name"] + The_Montha_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } else if (!(System.IO.File.Exists(dr["UNC_Path"] + @"\" + dr["File_Name"] + The_Date + dr["File_Extension"]))) RowsToDelete.Add(dr); } // remove rows from source set foreach (System.Data.DataRow dr in RowsToDelete) DT.Rows.Remove(dr); } protected void DDLDepartment_SelectedIndexChanged(object sender, EventArgs e) { System.Web.HttpCookie CookE = new System.Web.HttpCookie("Reports_Page_Group"); CookE.Values.Add("Selected_Group", DDLDepartment.SelectedValue); CookE.Expires = DateTime.Now.AddMonths(2); Response.Cookies.Add(CookE); } protected string GetMyImage(string File_Extension) // Returns URL based of file type { switch (File_Extension) { case ".html": { return "images/Dashboard/Icons/IE.png"; } case ".xls": { return "images/Dashboard/Icons/Excel.png"; } case ".xlsm": { return "images/Dashboard/Icons/Excel.png"; } case ".xlsx": { return "images/Dashboard/Icons/Excel.png"; } default: { return "images/Dashboard/Icons/Other.png"; } } } // This function returns the URL to the report file requested on DataBind protected string ReturnUrl(string UNC_Path, string File_Name, string File_Extension, string Frequency) { DateTime SelectedDate = System.Convert.ToDateTime(this.txtDate.Text); UNC_Path = UNC_Path.Replace(@"K\", ""); string NuPATH = ""; if (Frequency == "") NuPATH = UNC_Path + @"\" + File_Name + SelectedDate.ToString("MMddyy") + File_Extension; else if (Frequency == "ASP Page") NuPATH = UNC_Path; else if (Frequency == "MTD") { NuPATH = UNC_Path + @"\" + File_Name + SelectedDate.ToString("MMyy") + File_Extension; string encodePath = HttpUtility.UrlEncode(NuPATH); return $"DownloadHandler.aspx?unc={encodePath}"; } else NuPATH = UNC_Path + @"\" + File_Name + SelectedDate.ToString("MMddyy") + File_Extension; NuPATH = NuPATH.Replace(@"\\", "http://"); NuPATH = NuPATH.Replace(@"\", "/"); return NuPATH; } } } 

And here is DownloadHandler.aspx.cs:

public partial class DownloadHandler : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string uncPath = Request.QueryString["unc"]; if (string.IsNullOrEmpty(uncPath) || uncPath.Contains("..")) { Response.Write("Invalid or missing file..."); return; } string fullPath = HttpUtility.UrlDecode(uncPath); if (File.Exists(fullPath)) { string filename = Path.GetFileName(fullPath); Response.Clear(); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); Response.TransmitFile(fullPath); Response.End(); } else { Response.Write("File not found."); } } } 

2 Answers 2

1

In order to make it work you will need to do some extra steps:

  1. At ajaxToolkit:CalendarExtender add OnClientDateSelectionChanged="onDateChanged"

  2. In the head add the JS function:

<head runat="server"> <title></title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script type="text/javascript"> function onDateChanged(sender, args) { var selectedDate = sender.get_selectedDate(); console.log(selectedDate); $.ajax({ url: "6steps.aspx/onCalendarDateChanged", data: "{newDate: '" + selectedDate.format("MM/dd/yyyy") + "'}", type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", }); } </script> </head> 

3. In the code behind define your function:

[System.Web.Services.WebMethod()] public static void onCalendarDateChanged(DateTime newDate) { } 

You can take it from here and adapted to your needs.

Sign up to request clarification or add additional context in comments.

Comments

0

The whole idea of the calendar popup is that it does NOT by design cause a post-back.

So, if anything inside of the update panel does cause a post-back, then you can of course get/see/use the value in the textbox. However, when the user changes a value in that text box, then no post back occurs.

However, you can add a event to the textbox (on text changed) like this:

 <label for="txtDate">Select Date:</label> <asp:TextBox ID="txtDate" runat="server" CssClass="form-control" OnTextChanged="txtDate_TextChanged" AutoPostBack="true" /> <ajaxtoolkit:calendarextender id="CalendarExtender2" runat="server" targetcontrolid="txtDate" format="MM/dd/yyyy" cssclass="calendarStyle" /> 

And now server side, you have this event:

 protected void txtDate_TextChanged(object sender, EventArgs e) { Debug.Print(txtDate.Text); } 

Since the text box (and autopostback=true) is inside of the update panel, then no apparent post-back on the page will appear.

Do keep in mind that a update panel does not prevent a page post-back, but results in a "partial" page post back, and this means that the page load event still fires each and every time that UP does a post-back.

And, in theory, you actually don't need to use the calendrer extender, since text boxes already have a calendar popup "built" in, and the AJ extender not really required.

So, you could use this:

 <label for="txtDate">Select Date:</label> <asp:TextBox ID="txtDate" runat="server" CssClass="form-control" OnTextChanged="txtDate_TextChanged" AutoPostBack="true" TextMode="Date" /> 

Using above markup, then the result is this:

enter image description here

However, your existing textbox can trigger an event if you add the auto post back = true, and use the OnTextChanged event of a text box.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.