AjaxFileUpload doesn't fire OnUploadComplete Event - asp.net

i am trying to get that AjaxFileUpload-Control(used in ContentPage) working. But it does not fire OnUploadComplete Event at server side
I am using version 4.1.60919.0 of the ControlToolkit. I have tried everything i found on the internet.
Here just a few steps:
Added enctype="multipart/form-data" method="post" to the form-element in my MasterPage
Nested the AjaxFileUpload into an UpdatePanel with UpdateMode=Always
Tried events UploadedComplete and OnUploadComplete, but stayed at the second one
Added a try-catch-block in the EventHandler to catch unknown exceptions and print the ExceptionMessage to a label on the site --> nothing happened
Tried it with(out) a ThrobberImage...
Many other tipps that did not work...
So, i hope we will find a solution together in this community. Heres my markup:
<%# Page Title="New Download" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="NewDownload.aspx.cs" Inherits="Internals_NewDownload" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<ajax:ToolkitScriptManager ID="ToolkitscriptManager" runat="server"> </ajax:ToolkitScriptManager>
<h1>Create a new Download</h1>
<ajax:AjaxFileUpload ID="FileUpload" runat="server" ThrobberID="ThrobberLabel" OnUploadComplete="FileUpload_UploadComplete" />
<asp:Label ID="ThrobberLabel" runat="server" Style="display: none;"><img alt="UploadingPicture" title="Please wait while uploading..." src='<%= Constants.DomainString + "/Data/Images/loading-small.gif" %>' /></asp:Label>
<asp:Label ID="DownloadLabel" runat="server"></asp:Label>
</asp:Content>
And this is my CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Internals_NewDownload : System.Web.UI.Page
{
private string m_LanguageCode;
protected void Page_Load(object sender, EventArgs e)
{
if (RouteData.Values.ContainsKey("LanguageCode"))
m_LanguageCode = RouteData.Values["LanguageCode"].ToString();
//if (IsPostBack)
// return;
if (!User.IsInRole("Administrator") && !User.IsInRole("Kunde") && !User.IsInRole("Mitarbeiter"))
Response.Redirect(Constants.DomainString + "/PermissionDenied.aspx");
Session[Constants.NonGlobalizedString] = true;
Session[Constants.MenuInfoSession] = new ClsMenuInfo("NewDownload");
}
protected void FileUpload_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string filePath = "~/upload/" + e.FileName;
DownloadLabel.Text = filePath;
}
catch (Exception ex)
{
DownloadLabel.Text = ex.Message;
}
}
}
Please, if you have ANY idea, do not hesitate to let me know it. I am very confused as i think that i just did in that howtos i found on the internet...
Thanks in advance!

Take into account that AjaxFileUpload control use contextkey QueryString parameter to detect own postback. I believe the reason of you issue is that this parameter lost in result of rewriting url.
I'm not expert in applying routing but in my opinion you need to register contextkey parameter in routing tables and tweak AjaxControlToolkit sources to use RouteData instead of Request.QueryString for retrieving it value.
Check this link for more info: AjaxControlToolkit Source Code

Related

How to stop dropdownlists where autopostback true, from posting to a new page set in postbackurl of button ASP.NET

The page performs as intended locally, the problem is when I upload to windows server and access it from there.
I have 2 to 3 dropdownlists displayed (depending on whats selected in the first dropdownlist)....
The first 2 dropdownlists where autopostback is set to true, will autopostback to the same page (intended performance). However, after I click the button within the form, and go back to original page, whenever there is a selectedindexchanged event on those dropdownlists, those dropdownlists are not autopostback to the same page anymore, they will now post to the postbackurl declared in the button (this is unintended and not the desired results)
How can I get those dropdownlists to stop from posting to new page on selectedindexchanged after I click the button and go back to original page?
Again, the dropdownlists do not autopostback to a new page until I click the button and then go back to that original page. At that point they then post to the postbackurl that is declared in the button. I don't understand why this is happening.
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder1" runat="server">
<div style="text-align: center">
<asp:Label ID="Label1" runat="server"></asp:Label>
<form id="form1" runat="server">
<asp:DropDownList ID="toolGroupDropDown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="toolgroupddl_SelectedIndexChanged">
</asp:DropDownList>
<asp:DropDownList ID="sizeDropDown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="sizeddl_SelectedIndexChanged" Visible="False">
</asp:DropDownList>
<asp:DropDownList ID="attDropDown" runat="server" Visible="False">
</asp:DropDownList><br />
<asp:Button ID="seeToolsButton" runat="server" Text="See Tools" Visible="False" PostBackUrl="/products" />
</form>
</div>
</asp:Content>
Here is some code-behind, not sure if this is relevant though...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing
{
public partial class WebForm12 : System.Web.UI.Page
{
public string listing;
public string attsize;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FillDropDown();
}
else
{
System.Diagnostics.Debug.WriteLine("postback occured");
}
}
protected void toolgroupddl_SelectedIndexChanged(object sender, EventArgs e)
{
listing = toolGroupDropDown.SelectedValue;
sizeDropDown.DataSource = this.GetSizeRecords();
sizeDropDown.DataTextField = "groups";
sizeDropDown.DataValueField = "groups";
sizeDropDown.DataBind();
sizeDropDown.Visible = true;
seeToolsButton.Visible = true;
toolGroupDropDown.Items.Remove(toolGroupDropDown.Items.FindByValue(""));
if (toolGroupDropDown.SelectedValue != "END")
{
sizeDropDown.AutoPostBack = false;
attDropDown.Visible = false;
sizeDropDown.Items.Insert(0, new ListItem("Choose Your Size", ""));
}
else
{
attDropDown.Visible = true;
sizeDropDown.AutoPostBack = true;
sizeDropDown.Items.Insert(0, new ListItem("Choose Your Size", ""));
}
}
protected void sizeddl_SelectedIndexChanged(object sender, EventArgs e)
{
if (toolGroupDropDown.SelectedValue == "END")
{
attDropDown.DataSource = this.GetAtts(attsize);
attDropDown.DataTextField = "NoOfAtts";
attDropDown.DataValueField = "NoOfAtts";
attDropDown.DataBind();
attDropDown.Visible = true;
}
else
{
attDropDown.Visible = false;
}
}
}
}
I only posted the code-behind that seemed relevant. Nothing else in the code relates to the question at hand.
The problem is page changing the action attribute. At Html level, initially you have:
<form method="post" id="form1" action="./WebForm12">
So dropdowns correctly post back to WebForm12. But when you press the button.
<asp:Button ID="seeToolsButton" runat="server" PostBackUrl="/products" />
The page does two things using Javascript:
Change the action attribute of the form to "/products".
Post the form.
When you navigate back in your browser, the form looks like this
<form method="post" id="form1" action="/products">
But now, dropdowns will post the form to /products, not WebForm12.
Solution: One way to fix that is adding this script to your aspx file
<script type="text/javascript">
window.onpageshow = function () {
form1.action = "./<%=System.IO.Path.GetFileName(Request.Url.AbsolutePath)%>";
};
</script>
However if your browser does not support onpageshow (e.g. IE10 or older), then you'd rather attach the function to click event of the dropdowns.

w3wp eating up memory and not giving it back

I have a classic asp.net page in .net 4.6.1.
It loads 4 MB of data (they want it on one page) and no matter I simplify it, the IIS Worker Process w3wp.exe eats up a Gig of data, and never expires anything or gives any memory back.
Why?
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<asp:GridView ID="gvSelectionList" runat="server" AutoGenerateColumns="false" CssClass="LPSCriteriaSelection" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="SerialNumber">
<ItemTemplate>
<asp:HyperLink ID="hlSerialNumber" Text='<%#GetSerialNumberText(Container.DataItem)%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Content>
Here's the code
using System;
using System.Collections.Generic;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(this.IsPostBack) return;
ExpandableSelections items = new ExpandableSelections();
if(items.Count == 0) return;
this.gvSelectionList.DataSource = items;
this.gvSelectionList.DataBind();
}
protected string GetSerialNumberText(object dataItem)
{
SerialNumberData item = (SerialNumberData)dataItem;
return item.SerialNumber;
}
}
public class SerialNumberData
{
public string SerialNumber { get; set; }
public SerialNumberData(string data) { SerialNumber = data; }
}
public class ExpandableSelections : List<SerialNumberData>
{
internal ExpandableSelections()
{ // Emulate database call
for (int i = 1; i < 72000; i++)
this.Add(new SerialNumberData("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"));
}
}
A call to Microsoft revealed calling .Dispose() on the grid itself will make it more readily available to Garbage Collection, but in this example the GC thread was often blocked (said they couldn't see by what -- antivirus?) and, because we only needed a read-only GridView,
I found it far better to simply replace the GridView with a classic <% FunctionCall(); %> and in that call write the html out directly with Reponse.Write().
This used far less RAM and would always return it on subsequent page loads.

Asp.net code behind not able to access controls in ascx

I am fairly new to the .NET scene and have run into a small problem with a simple asp.net app and accessing controls defined on in a .ascx file in the code behind.
Here is my Default.ascx file:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<p>
<asp:Label AssociatedControlID = "userText" AccessKey = "L" runat="server" ID="userLabel">Username</asp:Label>
<asp:TextBox ID = "userText" runat="server" MaxLength="20" ></asp:TextBox>
</p>
</asp:Content>
Here is the Default.aspx.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Page_PreInit(object sender, EventArgs e)
{
userLabel.Text = "Hello!";
}
}
As you can see, pretty straight forward, all I am trying to do is change the text property of a label programmatically. However when I run this I am getting a NullReferenceException, userLabel is not set to an instance of an object. Shouldn't userLabel be a property of my _Default class? I tried explicitly setting userLabel as a property but I get an compile time error saying that userLabel already has a definition.
I imagine I am missing something very simple here but I'm not sure what it is. Could anyone tell me what I am doing wrong? Thanks much!
Page_PreInit is called before controls are rendered. Try adding your code to the Page_Load method.
See Life-Cycle Events section in http://msdn.microsoft.com/en-us/library/ms178472.aspx
Controls are not available until they are initialized; the control has not yet been created at the PreInit event which is why you cannot access it.
Setting values like you are doing should generally be performed at the Load event, or at least after the page Init event has fired.
As you can read here, in the page_perinit you cannot access control because they does not yes exist.
Is a good practice apply theme and personalization during this event, not access the state of the controls
Initialization of controls should be done on Page_Init.
protected void Page_Init(object sender, EventArgs e)
{
userLabel.Text = "Hello!";
}
First of all, you can't simply access label in user control with userLabel.Text. You need to get with Label lbl = (Label)UserControlID.FindControl("userLabel"); in your parent page. (But what you need is to set vale of Label in UserControl from Parent page.)
So I would do as:
Put property in UserControl:
public string UserName {get; set;}
protected void Page_Load(object sender, EventArgs e)
{
userLabel.Text = this.UserName;
}
In page load event of Parent Page, set property value:
protected void Page_Load(object sender, EventArgs e)
{
UserControlID.UserName = "Hello!";
}
Page_Load of parent page will call before usercontrol's page load and it should be ok.
I don't see any label named userLabel. The name of your label seem to bel userText.

Required field validator for multiple dropdown lists in an aspx page

I have an aspx page which has 18 (yes 18) dropdown lists and 18 text boxes. Each dropdown needs to be selected and each textbox needs to be filled. Dragging and dropping required field validators on these 36 controls and maintaining them is a painful task and does not seem to be the logical option as all I need is for the user to select a value from the dropdown.
Is there anyway I can loop through all these dropdown controls and textbox controls, check if they are empty and display warnings to users accordingly? Client-side validation solution or server side validation solution is fine with me.
Use a CustomValidator and have a client script function that makes sure every text box/drop down has a value.
One suggestion is to loop through all the controls on the page, use recursive function to dynamically bind RequiredFieldValidator to the found controls. You can tweak my code to suit your needs.
This code has some drawbacks though:
Use control.ID instead of associated label text
Adding RequiredFieldValidator to the page.controls will modify its ControlCollection. This will break the foreach method. Thus, I can only add RequiredFieldValidator to Panel instead.
.aspx
<asp:Panel ID="pnlValidation" runat="server">
</asp:Panel>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" />
<asp:DropDownList ID="DropDownList2" runat="server" />
<asp:DropDownList ID="DropDownList3" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" />
.cs
protected void Page_Load(object sender, EventArgs e)
{
AddValidator(this);
}
private void AddValidator(Control ctrl)
{
if (ctrl is TextBox || ctrl is DropDownList)
{
RequiredFieldValidator rfv = new RequiredFieldValidator();
rfv.ControlToValidate = ctrl.ID;
rfv.Display = ValidatorDisplay.Dynamic;
rfv.ErrorMessage = ctrl.ID + " is required<br />";
pnlValidation.Controls.Add(rfv);
}
foreach (Control subctrl in ctrl.Controls)
AddValidator(subctrl);
}
If you are dynamically generating the textboxes and dropdownlists, you would probably want to dynamically generate the validation controls as well, but if all the drop down lists and textboxes are static you can use the following:
Use a CustomValidator Web Control, write client side javascript method that checks all the properties of the drop down lists and the textboxes and configure the web control's ClientValidationFunction with the function and set EnableClientScript=true. Also, b/c not all users have javascript enabled, plus to be sure as it is best practice, always also create a server side validation function as well and call Page.IsValid() on the submit action.
.aspx Sample Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"
Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function ValidateMe(sender, args) {
var txt = document.getElementById("txt");
if (txt.value != "")
args.IsValid = true;
else
args.IsValid = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox id="txt" runat="server" />
<asp:CustomValidator ClientValidationFunction="ValidateMe" ID="custval"
runat="server" ErrorMessage="Fail" onservervalidate="custval_ServerValidate" />
<asp:Button ID="btn" runat="server" Text="push" onclick="btn_Click1" />
</form>
</body>
</html>
c# codebehind sample code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void btn_Click1(object sender, EventArgs e)
{
if (Page.IsValid)
{
btn.Text = "PASS";
}
else
{
btn.Text = "FAIL";
}
}
protected void custval_ServerValidate(object source, ServerValidateEventArgs args)
{
if (txt.Text != "")
custval.IsValid = true;
else
custval.IsValid = false;
}
}

ASP.NET page with base class with dynamic master page not firing events

I am feeling that I have terribly wrong somewhere. I was working on a small asp.net app. I have some dynamic themes in the \theme folder and have implemented a page base class to load the master page on the fly. The master is having the ContentPlaceHolder like:
<asp:ContentPlaceHolder ID="cphBody" runat="server" />
Now I am adding pages that are derived from my base class and added the form elements. I know, Visual Studio has problem showing the page in the design mode. I have a dropdown box and wish to add the event of onselectedindexchange. But it is not working. the page is like this:
<%# Page Language="C#" AutoEventWireup="true" Inherits="trigon.web.Pages.MIS.JobStatus" Title="Job Status" AspCompat="true" CodeBehind="JobStatus.aspx.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="Server">
<div id="divError" runat="server" />
<asp:DropDownList runat="server" id="jobType" onselectedindexchange="On_jobTypeSelection_Change"></asp:DropDownList>
</asp:Content>
I have also tried adding the event on the code behind like:
protected void Page_Load(object sender, EventArgs e)
{
jobType.SelectedIndexChanged += new System.EventHandler(this.On_jobTypeSelection_Change);
if (!IsPostBack)
{
JobStatus_DA da = new JobStatus_DA();
jobType.DataSource = da.getJobTypes();
jobType.DataBind();
}
}
protected void On_jobTypeSelection_Change(Object sender, EventArgs e)
{
//do something here
}
Can anybody help?
Regards,
set AutoPostBack="true" on your dropdown

Resources