Update Panel AsyncPostBack and PostBack triggers - c#

I have a page in which much of the HTML is generated by client side script (JQuery). I added a server side ASP.NET File control to upload files to server.
Now files are getting uploaded on the button click, which causes POSTBACK and so all the textboxes Company Name, Street Name, City Client etc are lost, as they were generated by JQuery.
I put the upload portion in UpdatePanel and registered AsyncPostBack Trigger, but then I am not getting HttpContext object at code-behind. I turned Async to a full postback using PostBackTrigger then the things became the same as before(i.e. without an update panel).
Now I have two questions from you people:
- What is the use of an update panel if it behaves in the same way as the page without an update panel. (PostBackTrigger)
- What should I do with the above problem?
CODE:
<asp:UpdatePanel ID="uploadUpdatePanel" runat="server">
<ContentTemplate>
<input id="fileField" type="file" runat="server" multiple="multiple" />
<asp:Button ID="uploadButton" runat="server" Text="Upload Documents" OnClick="uploadButton_Click" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="uploadButton" />
<%--<asp:PostBackTrigger ControlID="uploadButton" />--%>
</Triggers>
</asp:UpdatePanel>

Basically, FileUpload controls don't work in UpdatePanels. I've run into this issue before and as far as I know, there's no way around it. You're just going to have to accept a full PostBack and work on saving user inputs.

I would respectfully disagree with CrazyPaste's declaration that the UploadFile control doesn't work inside an update panel. I spent hours on this problem and finally found the answer on an obscure five-year-old post on the asp.net forums.
Check to see if your .aspx <form> tag looks like this:
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
If it is an unadorned tag like <form id="Form1" runat="server"> that's probably your problem.
The majority of responses I found elsewhere mentioned setting the update triggers, as you have, and is correct, but setting the triggers is useless if your form tag is not correctly configured. Nowhere except on the 2007 forum page was this suggestion made. It works great now.
I hope this helps!

Related

What is the correct way to put multiple controls inside update panel?

I have one registration form which contains 3 to 4 dropdown controls and 2 datepickers and now when dropdown controls value are selected(selectedindex change are fired)
then i dont want my page to postback.
I have use update panel to stop this behaviour of post like below:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<%--Update Panel for date picker%>
<asp:UpdatePanel ID="UpdatePanelDatepicker" runat="server">
<ContentTemplate>
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
</ContentTemplate>
</asp:UpdatePanel>
<%--Update Panel for Dropdown--%>
<asp:UpdatePanel ID="updatepaneldata" runat="server">
<ContentTemplate>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</ContentTemplate>
</asp:UpdatePanel>
</ContentTemplate>
</asp:UpdatePanel>
So i just wanted to ask that is this correct way to put multiple controls under update panels??
Subscribe to ajax event of initializeRequest on client-side. In this event we can cancel an ajax postback if we need to.
The initializeRequest method is raised before processing of the asynchronous request starts. You can use this event to cancel a postback.
In this event, we will check if an async postback is being initiated due to ddlCountry, and if yes then we cancel the ajax post back so no post back occurs.
To solve your problem just do the following : Add following JavaScript to your aspx page. In code below, the pageLoad method is automatically called by ASP.Net Framework on client-side when browser loads the page and after all scripts have been loaded as well as all client-side objects created.
JavaScript to cancel combobox post back
<script type="text/javascript">
function pageLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CancelComboBoxPostback);
}
function CancelComboBoxPostback(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'ddlCountry') {
args.set_cancel(true);
}
}
</script>
The following is only a recommendation and not a part of the solution to your specific problem: Also, I would recommend to stay away from nested update panels as this can cause unexpected results if developer is not aware of how nested update panels work. In your situation, a single update panel should suffice as in markup below instead of nested update panels that you have used in your original markup.
Markup without nested update panels
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</ContentTemplate>
</asp:UpdatePanel>
Honestly, the UpdatePanel I find is more trouble than it is worth.
UpdatePanel controls are a central part of Ajax functionality in
ASP.NET. They are used with the ScriptManager control to enable
partial-page rendering. Partial-page rendering reduces the need for
synchronous postbacks and complete page updates when only part of the
page has to be updated. Partial-page rendering improves the user
experience because it reduces the screen flicker that occurs during a
full-page postback and improves Web page interactivity.
I often find the controls implementation causes more problems then it is worth. So I often implement my own Ajax services, to handle such logic. You can do this the old school way, quite easy.
// Create .aspx page, to be our service.
public class ControlUpdateService
{
protected void Page_Load(object sender, EventArgs e)
{
// Use an approach to determine which control type, and model to build.
// You would build your object, then use Newtonsoft.Json, to serialize, then
// return the object, via Response.End(object).
}
}
Then your page would Ajax the data, hit the service, then build your control via the .success in the Ajax call. If you do this approach, you commit to saving your data via Ajax as well. Keep that in mind. As I was answering this question, I can't help but feel your problem actually stems from the control doing an AutoPostback. Which you can actually disable.
AutoPostBack = "false";
Telerik may be different, but the documentation should clearly indicate how to disable this feature. Which would eleminate your need for an UpdatePanel all together. Allowing you to save your data, on PostBack correctly.
Use telerik Ajaxloadingpanel except UpdatePanel this is good for your code try this Example
<telerik:RadAjaxLoadingPanel ID="rlp" runat="server" Skin="Metro">
</telerik:RadAjaxLoadingPanel>
<telerik:RadAjaxPanel runat="server" LoadingPanelID="rlp" skin="Metro">
<telerik:RadDatePicker ID="rdpDate1" runat="server">
</telerik:RadDatePicker>
<telerik:RadComboBox ID="ddlCountry" runat="server">
</telerik:RadComboBox>
</telerik:RadAjaxPanel>

How to stop refreshing the page

Is there any chance to stop the page to refresh on every pressed control?
For example: I change the selection of a DropDownList and the page refreshes. It just feels weird.
I do it with a form tag runat="server"
Try using UpdatePanel and here you can find how to use the update Panel sample code.
easiest way to stop refeshing
Regarding PostBack:
PostBack is the name given to the process of submitting an ASP.NET page to the server for processing. PostBack is done if certain credentials of the page are to be checked against some sources (such as verification of username and password using database). This is something that a client machine is not able to accomplish and thus these details have to be 'posted back' to the server.
What is AutoPostBack Property in ASP.NET:
If we create a web Page, which consists of one or more Web Controls that are configured to use AutoPostBack (Every Web controls will have their own AutoPostBack property), the ASP.NET adds a special JavaScipt function to the rendered HTML Page. This function is named _doPostBack() . When Called, it triggers a PostBack, sending data back to the web Server.
Understanding PostBack
Try putting update panel for dropdown with triggers
<asp:UpdatePanel ID="upSetSession" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlMyList" runat="server"
onselectedindexchanged="ddlMyList_SelectedIndexChanged"
AutoPostBack="true">
<asp:ListItem>Select One</asp:ListItem>
<asp:ListItem>Maybe</asp:ListItem>
<asp:ListItem>Yes</asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlMyList"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
From asp.net:
Perhaps the most visible feature of the ASP.NET AJAX Extensions is the ability to do a partial or incremental page updates without doing a full postback to the server, with no code changes and minimal markup changes. The advantages are extensive – the state of your multimedia (such as Adobe Flash or Windows Media) is unchanged, bandwidth costs are reduced, and the client does not experience the flicker usually associated with a postback.
Integrate partial rendering into your project. Have a look at this link.
Also OnClientClick="return false;" may help but adding OnClientClick="return false;" on every button, is not a good idea. Partial rendering and AJAX is the better solution.

How to avoid AutoPostBack in a FormView?

I have an inherited ASPX page which has a FormView within a Form tag.
ie:
<body style="margin:0px;" bgcolor="skyblue">
<form id="form1" runat="server" action="Default.aspx">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="background-color: #87ceeb; vertical-align: top; text-align: center;">
<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" DataSourceID="SqlDataSource1"
OnItemInserting="FormView_Inserting" OnItemInserted="FormView_Inserted" BackColor="#00C0C0" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px">
<InsertItemTemplate>
etc
etc
As you can see I am using Ajax because further down the form there are CalendarExtender controls to handle dates.
The date textbox fields all have AutoPostBack="true" because the program would do nothing on the server side. ie: no events were firing. This was happening across all browsers - IE, FF and Chrome. Don't care about Safari, etc at this stage.
The point is I think I have fallen into "autopostback hell", where too many controls that do validation and other control manipulation have AutoPostBacks set to "true".
What is the better way to handle situations where controls such as textboxes, dropdownlists, etc need to perform actions before the form is SUBMITted? I would assume this is a common requirement in any form development project.
I saw somewhere (link) that wrapping FormView controls inside an UpdatePanel and ContentTemplate avoid the use of AutoPostBack. Can someone please explain some more on that?
Thank you
UPDATE
Setting my controls to AutoPostBack="true" is not a solution, because it upsets other areas of my DetailsView control and they do a postback as well. Again I suspect I have to wrap the formview inside something like an UpdatePanel to avoid autopostback entirely or do the data manipulation entirely in JScript, which I hate. But I may not have any choice.
It depends on what kind of validation you are doing. If you are doing simple validation (like required fields or regular expression validation) then you can just do the validation in javascript; no post back is required. There's even an <asp:RequiredFieldValidator> and <asp:RegularExpressionValidator> that you can use.
If you need to validate your data against the database, then you need to make a server call somehow. If you don't want to do a full page refresh, then you need to use AJAX. The easy way is to wrap each field that needs server-side validation in an <UpdatePanel>. For example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server"
ChildrenAsTriggers="True" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" />
<asp:Label ID="Label1" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
Even though AutoPostBack is true, it will only update the contents of the <UpdatePanel>, so it won't disrupt your other content.
As a note, UpdatePanels will still post all of your form data with each partial post back. (The benefit it that the response only updates the contents of the UpdatePanel, not the entire page.) What this means is that if you have a large form with a lot of fields, you could be sending a lot more data than you want over the wire, because the AJAX post back will post the value of every field back to the server, when you really only need the value of one field. To avoid this, you can use page methods instead of update panels. However, they are a lot more work since you need to write a bunch of javascript.

Why does using file upload in a user control with ajax update panel not work?

I'm trying to create a user control for upload and download attachment in my web application.
In my user control, i'm using asp.net update panel for upload and download files, and i use my user control in a <dive>...</dive> tag that display style is none.
Everywhere when i using this user control, i'm trying to set <dive>...</dive> tag display style to show user control, and i'm using below code for display this user control in modal popup mode :
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender" runat="server" CancelControlID="CancelButton" DropShadow="true" PopupControlID="PanelMain" PopupDragHandleControlID="PanelHeader" TargetControlID="btnFileOperation" />
In my user control i write the same below code:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:FileUpload ID="fileUploadImage" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload Image" OnClick="btnUpload2_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text="Image uploaded successfully." Visible="false"></asp:Label><br />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
Please wait image is getting uploaded....
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload" />
</Triggers>
</asp:UpdatePanel>
But when i want access to FileUpload.PostedFile or FileUpload.HasFile properties in code(click event of upload button), these properties are null.
What could be the reason for this problem? and How to fix it?
I spent hours on this very problem, and finally found the answer on a five-year-old asp.net forum post: UpdatePanel + FileUpload + PostBackTrigger doesn't seem to work. To boil it down, on my site.master page the <form> tag had simply been:
<form id="Form1" runat="server">
The post from 2007 suggested changing it to:
<form id="Form1" method="post" enctype="multipart/form-data" runat="server">
Works great! I don't understand why, but it does.
The bulk of the answers I found all over the net -- including several on StackOverflow -- suggested simply creating a postback trigger for the update panel. None of the variations of that worked for me. About five minutes before quitting time, I found this obscure page on the asp.net forums. One of the best feelings is getting a problem solved right before it's time to go home.
I hope this helps you.

how to upload an image file without any postback in ASP.NET

I am uploading a file using the <asp:FileUpload> and <asp:button> controls but I want to do it without a postback. On button click I execute the following code.
protected void btnUpload_Click(object sender, EventArgs e)
{
string strFileName = Path.GetFileName(FileUpload1.FileName); //fileupload1 is the <asp:fileupload ID
FileUpload1.SaveAs(Server.MapPath("~/UploadFile/" + strFileName + ""));
imgUpload.ImageUrl = "../UploadFile/" + strFileName + ""; //imgupload is the <img ID on which I am showing the image after upload
imgUpload.Visible = true;
}
After uploading the file I am showing the saved image from the specified folder in my project solution, but on clicking the upload button the whole page gets loaded and I don't want the postback on clicking the upload button.
just add the script
<script language="javascript">
function Change(obj) {
__doPostBack("<%= btnUpload.ClientID %>", "");
}
</script>
Call the script in your button click event like this
<pre>
onchange="Change(this);"
</pre>
Your image control added in the update panel with contentTemplate
<asp:FileUpload ID="imgFileUploader" runat="server" />
<asp:Button ID="btnUpload" runat="server"
Text="Upload" onclick="btnUpload_Click" onchange="Change(this);" />
<br />
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<img id="imgOrginal" runat="server" style="height: 200px; width: 200px;" />
</ContentTemplate>
</asp:UpdatePanel>
for more details
if you are using ASP.Net file uploader then is is not possible.. you can use Ajax file uploader for this purpose
Best way to upload images without any postback, you can try AsyncFileUpload control in Asp.net Ajax. A good example is here :-
http://www.aspsnippets.com/Articles/Using-ASP.Net-AJAX-Control-Toolkits-AsyncFileUpload-Control.aspx
Thankyou
I think you are asking about uploading files through partial request. Using ASP.NET file upload control it is not possible. Even it is wrapped inside update panel, it will not work. It needs to have synchronous trigger to make it work, that means it does full post back.
If you are using ASP.NET AJAX, checkout asyncfileload control and newly added 'Ajax file upload' control. These controls are present in Ajax control tool kit. Please go through the documentation since each have their limitations.
If they doesn't suit your needs, try for open source Ajax file upload controls like neat upload etc.
You can't do this using simple ASP.NET WebForms.
Do some research into what is known as the page lifecycle. Code behind methods like the one you've included are / can be executed only as part of a postback or server-side action.
If you want client-server interaction without a postback then you need to use javascript. You can use javascript alongside ASP.NET, and I believe there is a Microsoft implementation of 'AJAX' in the .NET framework.
You need to use ajax for this purpose. There are plenty of examples available on internet. Just google it.

Categories

Resources