Why do I have to force an AutoPostBack="true"? - asp.net

ASP.net 2.0, Visual Studio 2005, and standard controls such as <asp:DropDownList>, etc require that I put in AutoPostBack="true" for there to be a call to the code behind. But why? Shouldn't that be happening anyway?
Thanks

Code behind runs on the server. HTML code and Javascript run on the browser.
A dropdownlist is an HTML element that runs on the browser. It can't do anything on the server without sending data back to the server. The means by which ASPX web forms send data to the server is via postback.
Sometime you don't want a dropdownlist to send data to the server. It really slows down the user experience to have to wait for something to cross the wire. To speed things up, you can disable the postback on the list control; the server will only get contacted when the user posts the whole form. At that point, the server can inspect the list control to see if its value has changed and take action.

No, this should not be happening anyway.
An asp:DropDownList is a control that generates a single drop-down list. This is rendered as a select tag to the client. A select tag is typically there to collect input from a user, not to submit a form.
Forcing AutoPostBack="true" is necessary because then you are causing a post-back whenever the selected index changes. While this can be useful, this is not the expected behavior of a select tag, and most developers are not going to want this action... for performance reasons... or if it is part of a larger form, it will interrupt user flow... etc.

The alternative would be they only call javascript (on the client) as opposed to making a round trip to the server (postback).
Javascript is faster since it is on the client and doesn't require a round trip to the server, but it can be disabled or changed by the user.

Related

Ajax FileUpload is hijacking the aspx

I have a very simple page I'm intending to use to show the contents of a network file. The target file is brought in with the Ajax Toolkit AjaxFileUpload control. It works, and I can see the file contents when stepping through the debugger. The offending behavior, however, is that once the file is uploaded, the codebehind loses all ability to update the page. I cannot write the file contents to a multi-line TextBox. I cannot even update a label on the page. Neither can I write hard-coded "Test Text" to the TextBox or Label.
There are no errors or exceptions throw. The code runs to completion without writing the contents to the TextBox.
<h2>
Encrypted File Viewer
</h2>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Label ID="ViewingLabel" runat="server" Font-Bold="false" ForeColor="Green"></asp:Label>
<br /><br />
<asp:Button ID="UnauthorizedExitButton" runat="server" Visible="true" OnClick="DoExit" Text=" Exit " />
<br /><br />
<Ajax:AjaxFileUpload ID="AjaxUploader" runat="server" OnUploadComplete="FileOpen" width="800px"></Ajax:AjaxFileUpload>
<br /><br />
<asp:TextBox ID="Viewer" runat="server" Width="800px" Height="500px" TextMode="MultiLine"></asp:TextBox>
In FileOpen()
string tempPath = Path.GetTempFileName();
string tempPath2 = Path.GetTempFileName();
AjaxUploader.SaveAs(tempPath);
myStrUtility.DecryptFile(tempPath, tempPath2);
Viewer.Text = File.ReadAllText(tempPath2); //Fails
// For testing - Debugging
ViewingLabel.Text = File.ReadAllText(tempPath2); //Fails
Response.Write (File.ReadAllText(tempPath2)); //Fails
I'm completely baffled by this, since I can see the decrypted contents of tempPath2.
Thank you in advance for any insights you can offer.
Ok, I have a few minutes.
If you have a bunch of text boxes on your screen. You fill them out.
(no postback has occured yet). So, ANY server side code that runs will NOT have use nor see nor be able to get use of those controls.
So, you enter some stuff into text boxes. You then select a file to upload. You then hit the upload button.
Now, your 3 server side events will run. But the WHOLE idea of AJAX is you don't have to do nor want a page post back to have occurred. And a page post back has NOT occured!
So, now when the 3 server side events (from ajax file upload run), we have:
Start of upload event - server side runs. But again, that code in the form behind will NOT have use of any controls changed.
Single file upload compilate - your server side event code runs. But again, due to no post back having occurred - then any control changed or text entered into controls is NOT available yet.
Final all files upload event - again server side event code runs, and again you can't get or use any controls on the form that changed.
Several solutions:
Any text boxes, or data entered or changed? You need some kind of "ok buttion", and that button does the post back - in that routine, you THEN turn on (display) the up-loader.
Now the user can select file(s), and start the upload. For the 3 ajax events (start of up-loading), single file done, and then all done event can all run server side with use of your controls.
So, just keep in mind that you can enter a bunch of data into the form, and then use the up-loader (select files, then upload button). For this whole process no page post back occurs
Worse? If you put a submit button on the page, and the user has selected files, and then decides to hit the post back? Well the ajax uploader does NOT persist the files selected during a post back. This is why I strong suggest you hide the up-loader (can't use visible, you have to use style).
The most simple solution is if you have a group or bunch of controls on the form that you need to set or will have data/changes made before they start a upload?
Put the group of controls in a up-date panel. And set auto post back for each of the controls. So, any control you edit will now cause a post-back. Now, such data is available in server side code. (and that includes the 3 ajax up-loader server side events).
Do keep in mind that this up-date panel will result in what is called a partial post back (the on-load event will fire).
So, the behavior you are seeing is not a surprise at all. You also can NOT hide/show or change values of controls in the 3 up-loader events because as noted, you will be changing values of controls, but the page has NOT been posted back. If you attempt to change controls in the 3 events, whatever you do will be lost if/when you/users do eventually post back the page. Remember, you have a stateless web page on the desktop.
If that stateless page has not (yet) been posted back, then the 3 ajax server side events can't see the client side browser controls at this point in time. And if your change controls in those 3 events, you are changing the controls sitting server side, but the web page is not going to be updated.
So, you either have the controls on the page do a post back BEFORE they select files and start up-load. As noted, I often "hide" the ajax file up-load. Let user enter some stuff, and then have a "ok - now lets up-load files". When they click that button, your server side code runs, you do whatever, and then turn on (display) the ajax up-loader. At that point then ajax upload events (the 3 server side events) can run, and that code now has a posted back copy of the client browser.
Now, assume the very last ajax event (all files uploaded) has occured. You can now try and modify controls on the page, but the page is still sitting client side. It has NOT been posted back. And you not going to be able to post that page back between the start of the up-loads, and when you finish. If you simply run a bunch of code in the final event and try to update controls and values on the page - you can't!! Because no post back has occurred and the controls and their values are still sitting client side.
Another way to achieve this goal is to use a client side javescript event tied to the LAST ajax event (all files done). However, that means the 2nd event (one file done, and save-as file) will NOT have use of controls if you start the up-load BEFORE the page has been posted back.
So, this means that if you going to use controls during the up-load (start to finish events), or run code in that final event that modifies controls? You need the page posted BEFORE you run the up-load process.
You can try can change all and any controls with code in that 3rd final server side event, but you modifying controls in the server side browser copy. You not see ANY changes take effect. It will thus seem like you cant modify anything.
So, in a good deal of up-loads? Well I want something to occur AFTER all is said and done. This means that the 3rd final event of the up-loader needs a client side event (and it will have a __dopostback() js command. The up-loader is VERY well built in that the client side JS events ONLY fire AFTER the server side events are complete.
So that final post-back trick/tip is ONLY of use if you want something to occur after all is said and done. But this tip don't help you get at controls in the 3 events, and as noted, unless you send the browser page back to the server, then any code you run server side will NOT show up in the browser. In other words, if you want some updates, or message boxes on the screen to update at the end of the load? You cannot use that 3rd final ajax code stub. You have to do a post back BEFORE you attempt to modify anything on the page.
(else you be modifying the server side copy of the browser without having posted back the client side browser copy that is "different" and not the same.
So, those 3 events can't modify any controls, since the page not been posted, and when you eventually do post the page, what controls you modify will be lost/overwritten when the client side browser post back occurs.
So you not losing the ability to modify controls on the page in that 3rd last event, but you modifyng a copy of the server side page - and you never see the changes.
So, with a standard asp.net buttion:
we have:
Post back (browser page goes to server)
Your code (any code behind) can run, can see, can grab/set/see/change any control on the form.
Now browser is re-sent back to client and displayed. (so you can see your server side code changes in those controls.
With the ajax uploader, no page post back has occured, and no re-rendering of the browser will occur. (those controls and events don't cause a post-back). So, you can't run server side code to change things, since you don't have a copy of the client side. And even if you do modify controls, no page is sent back to the client side to re-display.
So, based on the above asp.net model and code behind? You can't change controls unless your server side code runs as a RESULT of a post-back.
So, either get your post back all done and wrapped up BEFORE uploader runs, since those 3 server side events can't modify controls, and will not see client side changes unless you do/did a post back BEFORE the upload starts.
Just put auto-post backs in the controls. But then auto post backs for the several controls does cause a whole page post back. So, you can "mitigate" this by placing the group of controls in a update panel. Or, as noted get all your controls loaded up and set with a post back that THEN displays the up-loader for the user to start.

How can I have minimal data do back and forth for an AJAX enabled GridView

I have a listview with 250 rows and 4 columns in my ASP.Net 4.0/C# application. The Rendered page size (from Trace) is 650,000 Bytes. The entire listview is in an update panel.
The listview facilitates view/add/edit/delete operations on the listview records.
Every POSTBACK action (i.e. edit click, delete click) causes a POSTBACK request of size 112,000 Bytes and an AJAX Response of ~650,000 Bytes.
The listview gets the data from a declarative data source (SQLDataSource) on the page. And the listview is bound on each round trip.
I want to reduce the data going back and forth in every call because on a slow connection, these AJAX calls take 2-3 minutes to complete.
What I have tried -
Removed the update panel over the entire listview and added an update panel over each:
ItemTemplate contents
AlternateItem Template contents
Edit Template contents
Insert Template contents
I was hoping that with the template in each row, it would reduce the size of the AJAX response since only the HTML for the update panel would come back. Unfortunately, it does not seem to work that way.
Any inputs on how the problem in my case can be solved?
Thanks in advance for looking this up.
The problem with an UpdatePanel is that you are not using real AJAX. Instead ASP.NET uses some really clever hacks to create the illusion of a partial page update. On the background, your whole page life cycle is executed. This also means that your complete ViewState is send back and forth.
If you want a faster experience, you should not use UpdatePanels. Instead, use plain HTML controls (preferably not even server controls) and use JavaScript and a server side webservice (such as WebAPI or a WCF service) to respond to the client side requests.
Those requests and response will only contain some JSON data and no markup. Your data can be kept to a minimum. If for example, a user removes a row, you only have to send the Id of the row to your service and it will return success or failure. The client will use JavaScript and maybe something like KnockoutJS to render the result. This will give you minimal overhead and a better performance.
The best possible way to do this is to not use the ASP.NET user controls and instead do this cleanly using JavaScript, JSON, HTML and a server side web service/http handler
That way you don't have to send large HTML responses from the server to client. You can also control when need to refresh and rebind your data.
I bet the whole size issue has to do ViewState. The reason being that on every postback, even if it's an AJAX postback the ViewState travels with it on every request. The only thing you can do, without making any changes, is to enable compression on the IIS side. This, at least, will send the response compressed and the browser will take care of decompressing it.
The best approach is not to use UpdatePanel and ScriptManagers at all and instead make AJAX requests using jQuery (or whatever framework you prefer) by invoking a WCF Web service. This will not trigger the full page lifecycle and will not send the ViewState on every request.

Server Control or HTML control

i want to know is there any difference between server controls and HTML controls in speed?
for example you want to create a log in page that have two textbox and a button for submitting data,you can do this with both server controls and HTML controls(client_side controls(input) ),do you prefer to use server controls or HTML controls and which one is more efficiently?
which one is faster?
You always want to validate on the serverside, trusting anything from the client is a big mistake
Server Controls must be executed on the server and a Render method is called to generate the HTML. Therefore they cost a little bit of performance on the server. Depending on the control, they emit data in the ViewState as well, which costs a little bit of additional bandwidth (or very much depending on the control).
It depends on the type of control you want to use. As soon as there is any serverside processing involved (read a textbox, handle a button etc.), I always prefer the asp.net server controls, because they provide much more functionality. But if the control is just sent to the client (such as images, tables, divs etc.) I use HTML controls.
I think the server side processing doesn't take much, it takes a lot longer to get data from a database. Of course it depends on the number of users as well, whether you have to optimize or not. But I would rather use OutputCache instead of not using asp.net server controls.
Hope this helps.
The main advantage of server control is that its wrapping a control as a .Net object. It gives you a medium to access your control and its properties from code behind.
HTML controls are usually won't be accessible at client side. However, you can make them available to code behind by adding runat="server" attribute.
With the assumption that you want to access the control from code, you can chose any of them.
Now if you really want to see the difference between the asp.net control (I guess this is what you have referred to as server control) and html control, its the difference between the WebControl and HTMLControl (parents of asp.net and html controls). You basically get two different sets of wrappers. ASP.Net controls come with lot of customization and the control set is a long list than tha HTML controls list.
If we assume that you want to do some basic stuff and there is no need to access the control from code, best thing is the HTML controls, because it would save the rendering effort from the server side.
One more catch here is, if you want to utilize server side resources, such as images stored in server side, you can't access it with simple consistantly. The postback may lose the path. It would expect a control with runat="server". Its again your choice, html or asp.net controls!!!
Server controls are simple html or combination of html controls with capability to post data to server.
I would prefer server side controls for simple login screen, with preliminary client side validations.
Efficiency of controls depends on the No. of round trips it is making to the server and amount of javascript logic it is executing.

What is the use of JavaScript?

Why do I need script on an aspx page?
Javascript will allow you to perfrorm client side coding, so to avoid having to post back to the server.
From Using JavaScript Along with ASP.NET
Working logic and application
processes on the client-side allows
browser based applications to seem
more responsive and to have more
"snappiness" to them.
For client scripting, i.e. validation. There are many scenarios where you need to execute certain logic on the browser's end.
Javascript runs on the client side. So if you want anything to happen or change without refreshing the whole page you use javascript.
There are a lot of things the server can't really do that well. For example if you want to manipulate the page. You could post the whole thing back to the server with some sort of action and get the server to give you a new page. Or you could just use javascript to change it for you and avoid the trip to the server. It is faster for the client and takes the load off of your server.
It helps in doing things on the client side, which essentially means you can :
reduce burden on your server
by doing less postbacks.
do a round of validations on the client
side itself if they are non critical.
Do some fancy stuff like animations etc with out contacting the server
There are a lot more implications/uses of using JavaScript.
For knowing more, remember google is your friend!
Thanks
I'm not sure if you mean why ASP.NET pages requires Javascript, or if you mean additional scripts on the page.
ASP.NET uses Javascript for several types of postbacks. If you for example have a LinkButton, a script is making a postback instead of the default action of the link.
You can use additional scripts on the page for visual effects and to verify data before doing a postback to prevent unneccessary postbacks. (Of course you should also verify the data on the server side to protect against malicious actions.)

Understanding Postbacks in ASP.NET

For example,
If I have a textbox with runat=server on a page, The value will be posted back to the server so I can access the properties in the code-behind.
However, under the following situations, does it still hold true?
A textbox with runat=server but does not appear in the function that is post back to. For example, a button is also on the page, when clicked a post back occurs and within the method that is raised, this textbox was not used.
Within a MasterPage, will a textbox residing on the Masterpage itself be posted back?
Because just thinking, isn't this mechanism bloated in nature?
If all input controls and its value are posted back on every single button click (even when the input control is not needed), doesn't this deteriorate performance?
Having just one Form Tag on the page really restricts us to using this mechanism?
Truly Understanding ViewState is a must read article on the subject of ASP.NET ViewState
There are several options to cut down on the bloat (and yes, there's a lot of it when dealing with lots of controls):
Use AJAX to post only the items required - although be careful to allow clients that don't have JavaScript enabled to still use the page/ site.
The MVC framework allows multiple form tags to be used so you can group sections if needs be.
Set the EnableViewState to false on pages/ controls.
Break up your pages into smaller ones.
Additionally, check out this brilliant graphical representation of the Page Life Cycle in ASP.NET.
Every input on the page is posted back fully unless you use ajax, because of the single form tag. Welcome to asp.net...
As long as the method that you're hitting on the server-side is a non-static member of the page's class, it'll have access to the textbox and all other controls on the page.
And yes, all controls rendered to the browser (whether in the MasterPage, user control, etc.) will be available on post-back.
You may want to look into Understanding ASP.NET View State.
There surely are performance hits with this architecture, but (depending on complexity of the page) it's usually not an issue from the server load perspective, because hardware upgrades are typically cheaper than additional programming hours spend on optimizing application performance.
With that said, (and as others have pointed out) look into using AJAX if you want to avoid whole page-level postbacks to the server.
Yes, it's all posted back, and yes it can cause bloat. I'm sure if you search for ViewState you will find plenty of people ranting about it and how to minimise it :)
Yes your text box will be available in both cases, yes it is bloated. This is where AJAX comes into play. Using AJAX you can send just the data you need.
If you want to send a minimal ammount of data, you could use a Page Method (static method on page decorated so the script manager builds javascript to call it or you could call it using jquery or other methods), or a script enabled web service works nice as well.
You also have viewstate which can get very large. ASP.Net MVC is a new paradigm instead of using WebForms which doesn't have view state, or post backs. It embraces HTTP instead of hidding it giving developers more control.
The textbox data would be posted back as noted. In addition to using Ajax, disabling view state greatly imporoves your page's performance though even then data in properties critical to the functioning of controls (Control state) would still be posted back.
If you didn't have postback for every control on the form, you wouldn't be able to access it in code-behind. I.e. if in your button press you wanted to modify the property of the text control you couldn't do that because ASP.Net would know nothing about the text control.
Since the communication between the server and the client is stateless and every time a page is server the server forgets all about it Postbacks are important if you want to work with the same page again. No matter what programming language you use, this or similar mechanism exists for processing server side code.
If you wish to minimize postback (viewstate size), do this.
Set enableviewstate=false on all controls that you don't want posted back.
Use AJAX and web services wherever possible (and don't use UpdatePanel).
Use HTML control as much as possible instead of ASP.Net controls.
Hmm.. There are some excellent suggestion in other answers and good links too.
You've pretty much hit the nail on the head with vanilla ASP.NET - it's not very good! In both the instances you describe the answer is yes - the textbox will be sent with the form.
The whole postback/ViewState problem is a bit of a pain, one of the first things any competent ASP.NET developer learns to do is avoid them!

Resources