asp.net postback with jquery ajax and jquery dialog - asp.net

We have a method on an asp.net page that is called on a button click. The problem is that the method take a long time to process. I've been asked to have the page call the method (or call the postback) and then display the jquery.ui dialog which will let the user know that this process could take a long time. I'm looking at serializing the asp.net form and doing a $.post() but to be honest I'm completely stuck on whether this will even work and how I can prevent the actual postback from happening and just displaying the dialog. Has anyone had any experience with doing this that can give me some pointers?
I found this http://dotnet.dzone.com/news/eliminating-postbacks-setting- but I'm not sure if it's a bit OTT. The article is a little long winded.
Hope someone can help.

That would be easier if you can use an UpdatePanel (which basically boils down to ASP.NET's way of doing what you're considering with the $.post(), but automatically gets the ASP.NET specific stuff right).
Then, you can do something simple like this: http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/

You can send a post request through javascript (AJAX) without using asp.net's ajax framework. So in other words do it manually. Ajax would be perfect in this case, because you are trying to show loading indicators on the front-end while you are waiting for a response from the server.
To do this, take the logic out of your button_click method and put it in a separate page (text.aspx see below). Then you can call that page like this (using JQuery):
$('#ProgressIndicator').show();
$.post("test.aspx", function(data){
alert("Data Loaded: " + data);
$('#ProgressIndicator').hide();
});
If you can't use JQuery in your project, see: AJAX

Related

AJAX, IIS, ASP.NET

I'm dipping my toes into web development. Based on various bits of advice, I'm going to start by getting a handle on html, css and javascript.
I'm interested in Ajax, I've had a look at the client side code and that looks straight forward enough, I'm slightly confused about what I do on the server side.
I'm using IIS and ASP.NET. I've had a google but I can't find anything that is either simple or current. There's a lot of talk about the Ajax toolkit, which I believe are controls which use Ajax (and may be retired??) Everything else seems to be based on old versions which I don't trust.
So, in really simple terms, what do I have to do in IIS to respond to an AJAX call?
Quick aside, I believe we can use JSON for object serialisation?? I assume I don't need to in the interests of getting a simple sample running?
So I have an Ajax call which will have one parameter, and I want to return "something" based on the parameter. What is the simplest code to achieve that with IIS and ASP.NET?
Thanks
An AJAX call is basically just a regular call to your website. The only difference is how the browser handles it - AJAX calls are done in the background with Javascript (the J in AJAX) and then does something with the data. You could take the URL that you're doing an AJAX call with and put it in your address bar and it'll return the exact same data. So, basically, what you do on the server side is exactly what you would do as if it were a form being submitted, for example.
As far as object serialization, yes, JSON can do that.
First of all, doing ajax has nothing to do with IIS; it has to do with ASP.NET.
There are essentially 2 ways to do AJAX in .net
1) Heavy use of the framework. You can put your asp controls (such as literals, gridviews, listbox...) in a control called an updatepanel. For this to work, you need to add a script manager to the aspx page. Then, when the user raises an event (for example, paging and sorting of a table), the request is handled by the framework and only the part of the page that's in the updatepanel is refreshed. The other way to raise events is by using the __doPostback function that comes with the asp.net framework. The downside of this method is that a lot of data needs to go back and forth between the user and the server so it can be slow. The upside is that you don't have to worry about generating the HTML since the asp controls handle it for you.
2) Heavy use of Json. With this method, you can use jQuery to call a page method or a web service. You send a json object to the server and you get a json object back. With jQuery, this is really easy. The downside of this method is that you're getting just the json data back: no formatted HTML. So, if you're looking to have a table updated, this method would be tedious because you'd have to recreate the entire HTML. However, the upside of the method is that it's very fast because only the raw data is transmitted. If you implement a web service, you don't even need to create an entire page.
What do you need to get from the server?
If you want to return "something" from the server that's "simple" (just data), I'd recommend a web service with jquery to trigger the call. If the return data is "complex" (html code for controls) then I'd recommend using MS ajax with the update panel.
Don't use the AJAX Control Toolkit, ASP.NET AJAX library, updatepanels or the scriptmanager control. Microsoft have pretty much ditched the lot in favour of jQuery and its Plugins (sensibly).
Here are just some of the ways you can use AJAX with jQuery in ASP.NET: Many ways to communicate with your database using jQuery AJAX and ASP.NET

aspx ashx mash-up

I'm retro-fitting a .aspx page with AJAX functionality (using VB, not C#). The codebehind populates the page with data pulled from a web-service. The page has two panels that are populted (with different data, of course) in this way. On a full page refresh, one or both panels might need to be populated. But populating Panel 2 can take a long time, and I need to be able to update panel 1 without refreshing Panel 2. Hence the need for AJAX (right?)
The solution I've come up with still has the old .aspx page with .aspx.vb codebehind, but introduces a Generic Handler (.ashx) page into the mix. Those first two components do the work on the user's first visit or on a full page refresh, but when AJAX is invoked, the request is handled by the .ashx page.
First question: Is this sound architecture? I haven't found a situation online quite like mine. Originally, I wanted to make the .aspx page into the AJAX handler by having the codebehind implement IHttpRequest, and then providing "ProcessRequest" and "IsReusable" methods, but I found I couldn't separate a regular visit to the page from an AJAX request, so my AJAX handlers took over even on the first visit to the page. Second question: Am I right to think that this approach (making the .aspx page do double-duty as the AJAX handler) will never work? Is it impossible to tell whether we're getting a full-page request or a partial-page (AJAX) request?
If the architecture is good, then I need to dynamically generate a lot of HTML in the .ashx file, right? If that is right, should I send HTML back to the client, or should I encode it in some way? I've heard of JSON encryption, but haven't figured out how to use it yet. So, Third question: Is "context.Response.Write" the only pipeline for sending data back to the client? And, if so, should I send back HTML or some kind of JSON-encoded objects?
Thanks in advance.
It sounds as if the page requires some AJAX functionality added to the UI.
Suggest using an UpdatePanel for each web form element that needs to have AJAXy refresh
functionality. That'll save you from having to refactor a bunch of code, and introduce a whole lot of HTML creation on your .ashx.
It'll be more maintainable over the long run, and require a shorter development cycle.
As pointed out by others, UpdatePanel would be a easier way - but you need to use multiple update panels with UpdateMode property set as conditional. Then you can trigger the update-panel refresh using any button on the page (see AsyncPostBackTrigger) or even using java-script (see this & this). On the server side, you may decide what has triggered the partial post-back and act accordingly by bypassing certain code if not needed.
You can also go with your approach - trick here is to capture the page output using HttpServerUtility.Execute in your ashx and write it back into the response (see this article where this trick has been used to capture user control output). Only limitation with this approach is that you can only simulate GET requests to your page and so you may have to change your page to accept parameters via query string. Personally, I will suggest that you create a user control that accept parameters via method/properties and will generate necessary output and then use the control on your page and in ashx (by dynmaically loading it in a temperory page - see this article).
EDIT: I am using jquery to illustrate how to do it from grid-row-view.
$(document).ready(function() {
$("tr.ajax-grid-row").click(function() {
$("#hidden-field-id").val($(this).find(".row-id").val()); // fill hidden filed
$("#hidden-button-id").click(); // simulate button click
});
});
You can place above script in the head element in markup - it is assuming that you have decorated each grid-row-view with css class "ajax-grid-row" and each row will have hidden field decorated with css class "row-id" to store row identifier or the value that you want to pass to server for that row. You can also use cell (but then you need to use innerHTML to get the value per row). "hidden-field-id" and "hidden-button-id" are client ids for hidden field and submit button - you should use Control.ClientID to get actual control ids if those are server controls.
JSON is not for that purpose, it is to pass objects serialized with a nice light weight notation, is you need to stream dinamically generated html using ashx, response.Write is what you have. You may want to take a look at MVC
Or you could use jquery if it's just html, the simpliest would be the load function, or you can look into Ajax with jquery. Since the ashx can be served as any resource it can be used in the load function.
I agree with #p.campbell and #R0MANARMY here. UpdatePanel could be the easiest approach here.
But then like me, if you don't want to go the UpdatePanel route, I don't see anything wrong with your approach. However, generating the html dynamically (entirely) at the back end is not a route I'll personally prefer (for the maintainence reasons). I'd rather prefer implementing a solution that will keep the design separate from the data.

JQuery with asp.net 3.5 and doing post/call backs

I currently have a simple form that when you click the "save" button will persist it to the database.
I would like to use JQuery to do the callback for me and popup a "Save completed" div window/div of some sort.
My only problem is how do I call the btnSave_Click() event from JQuery?
If I use PageMethods the method would have to be static and therefore lose access to my textboxes and other page controls?
Thanks,
Goosey
Are you explicitly trying to avoid passing the values of the input controls? because that would be much easier.
Using a lightweight jQuery call to do the post but then expecting a full control hierarchy in the code behind to pull data out? What's the intent here? If you require that, it would probably be easier just to submit the page, and register javascript to run to pop the success message up on load.
Personally, I think the page method route and $.ajax or $.post is a much cleaner, separate way to solve the issue. That way you can just show the popup as part of the success callback.
You can use onClientClick
Have a look at the jQuery Form Plugin, it can change existing forms into Ajax forms.
You need to set __EVENTTARGET to the id of the control that you want to simulate causing the postback if you want to use the same handler. I seem to recall having to replace the underscores with dollar signs as well, but I could be wrong on that. The hidden inputs, __EVENTTARGET and __EVENTARGUMENT, are used by the framework to identify which control caused the postback. There's a nice discussion of the server side issues in this blog post, though it doesn't talk about AJAX. Google for __EVENTTARGET and postback for more info.

How to call a asp.net page asynchronously using JQuery

I want to call a aspx page method asynchronously using JQuery
You can use AJAX in jQuery to call a page method without too much trouble. Though I guess it depends on what you're trying to do. Sometimes it's better to contain your asynchronous methods inside a web service or web handler instead of the page.
I've posted on how to do this here. But it's not an example on how to do it with a page method, though the process is very similar.
BTW, a quick web search will turn up MANY results on what you're trying to do.
This example is very good.

How to use jquery form plugin with asp.net?

in asp.net 2.0 (not mvc), the form's action is to itself. how can I use the forms plugin to send information to server?
I need to send data from the form (let's say name, email, comment) and to display the result on the client side.
Any ideas?
Thanks,
Dave
ms ajax? if i use update panel, i don't need jquery. i want to use jquery and the form plugin (plus the validation plugin) only. no microsoft ajax for me, thank you!
just look at the trafic they produce in firebug to understand why.
It depends on how much of asp.net you want to use during the form submit. I am using the forms plugin in this same way but you need to think in terms of a more classic web model.
The forms plugin does a 'submit' which does not include any viewstate information. That is to say, if you try to get a value like so
sName = txtName.text
the text for txtName will be blank. But if you use your request object you should be able to pull back the value provided your know the control's UniqueID
sName = Request.Form(txtName.UniqueID)
Then what I would do is use the form plugin's success: callback to run an ajax call that will pull back your results. You can use ms ajax WebMethods for this, and you can call the webmethods directly from jquery without the need for the ms script manager. In this case, the WebMethod is returning the html I want displayed on the page.
$(form).ajaxSubmit(function(){
success:function(ret){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
url: "SomePage.aspx/SomeWebMethod",
success: function(msg){
$('#somediv').html(msg);
}
}
});
More info on calling ms ajax with jquery here
Because of the way viewstate is tightly coupled to the form in ASP.NET, unless you set up a service to accept the request I'm not sure if this is going to be possible. If you don't want to use viewstate, then you could just use a normal HTML form on the aspx page and submit that to a service that returns your expected results.
When you submit an asp.net form to postback, it sends everything back through the page lifecycle, I don't think there really is anything for a jQuery ajax request to talk to. You could setup a WebMethod on the page, which essentially exposes a service and you could get the jQuery request to talk to that, but I'm not conviced that it would work.
However, you can do ASP.NET AJAX with the MS libraries without using UpdatePanels, see this article for a good rundown of what you can do with WebMethods and the ajax javascript libraries
I ran into this problem today and eventually solved it using the following combination of hacks:
Suppose you have a search page and a results page and you have a form on the search page that you want to post to the results page and load via ajax using the jquery forms plugin. You need to do the following:
Create a Search.aspx page and a Results.aspx page
ASP.NET webform pages have a single form on a page with and id of aspnetForm but the action will always be set to post to itself, so the first thing you need to do when you load the Search.aspx page is to change the action of the aspnetForm to be Results.aspx like this:
$('#aspnetForm').attr('action', 'Results.aspx');
You then need to deal with viewstate so that when you POST from Search.aspx to Results.aspx you don't get invalid viewstate errors. To do this just remove the viewstate variable from the page like this:
$('#__VIEWSTATE').remove();
then you should be able to set up the #aspnetForm to use the jquery forms plugin like so:
$('#aspnetForm').ajaxForm();
This then allows you to post to the Results.aspx webform. This is just a start to get you going in the right direction, but basically it comes down to needing to change the action that the aspnet form posts to and then removing viewstate.
I currently use a mix of asp.net and jquery and the way i solved the issues with the page life cycle and such is to simply not use the autopostbacks and asp.net buttons to submit the form.
I use either ajax calls attached to simple html buttons or, when i really want to submit the entire page i use the __doPostBack(eventTarget, eventArgument) javascript function.
These articles were useful to me:
Understanding the JavaScript __doPostBack Function
Calling __doPostBack in javascript
It doesn't seem VS08 works for you, but others may be interested:
I went to a MSDN Roadshow the other day that seemed to make it very easy.
Scott Gu's blog has this:
http://weblogs.asp.net/scottgu/archive/2008/11/21/jquery-intellisense-in-vs-2008.aspx
It doesn't work, as ASP.NET force you to put everything within a server form as long as you use server control (this is the way how it handles postback). The primary problem you would have is HTML does not allow nested form anyway, so you can't even use jQuery to find the form element (thats my experience with FF3)
The good answer (but hard to achieve)- throw away WebForm and use MVC.
The compromise workaround- I did a small plugin myself which converts a div into an ajax submit with the div abused with method="post" and action="url" dress up, then utilize jQuery Form Plugin to serialize, submit with a plugin pattern. It doesn't do File Upload though (as that requires IFrame, I think its still feasible, but take some more hack). The code is in my client's project so I still dont have permission to post it as a plugin. However I think this is not too hard to do it once you know the theory :)
Really, aim for the good answer (get rid of WebForm) next time. Its not just jQuery Form going to hurt you, there's a lot more pain you have to take if you decided to do jQuery + Web Form, if its not my client's requirement I would never take this path.

Resources