As far i learned ....AJAX is used for partial page refresh (overcoming the flickering effect in the web page) ....Is there any other features in AJAX....
Technically Yes. Ajax is used for "partial page" refresh there by eliminating the complete page refresh. There are 2 main advantages
Data transfer : Data transfer (To and from the server) is less compared to the entire page refresh
Better User experience : Since the user will not be seeing a blank page it gives the user an illusion of interacting with the site.
What can be done using AJAX is an ever ending list.
Ex: Gmail uses AJAX for it email. If you are using gmail and compare it with other email providers you will know the difference.
Facebook has rich AJAX features in its site.
SO uses AJAX for comments
I think What AJAX cannot do will be easier to mention. For example
AFAIK web browsers cannot maintain the view state of the AJAX enabled website.
Some AJAX enabled websites do not render properly in mobile browsers.
Anythign more?
Your question is a bit confusing, but you can do Ajax with ASP.NET. You can do partial page refreshes with Ajax among other things using the UpdatePanel in ASP.NET. You may also want to look at jQuery for a simpler more lightweight Ajax solution.
I think you're very mistaken. If AJAX had been created only to solve the problem of partial page refresh/page flickering, it would not have revolutionized the web in the way it has.
The single biggest advantage offerred by AJAX is Client-to-Server Communication that is initiated based on some action on the client. This instantly gives us the ability to make the web much more responsive and user friendly without users having to wait for page reloads and postbacks.
I would suggest that you spend some time researching the subject. Read up on the Wiki article on AJAX.
As far as ASP.NET is concerned, AJAX integrates very well into it. Mature AJAX frameworks such as ASP.NET AJAX and Anthem.NET obfuscate much of the internal details of the XmlHttpRequest.
Ajax has let me add some great new features to my web applications with the free Ajax toolkit. See the link
Ajax Examples
They do not come with out their issues but once you learn how to use them they can really add to the the users experience in you site.
ASP.NET uses as you know UpdatePanel for partial page refresh using AJAX.
A less known feature is something .NET calls web methods. This is really AJAX calls that is not connected to the GUI part of the page. You can declare (server-side) a method as a WebMethod, and in the client side, you can call that using JavaScript.
Example:
This example shows how to get the value of a session variable. Note that the method must be Shared - which means that it does not know of any member values on the page object.
As for all ASP.NET AJAX functionality, you need to have a ScriptManager element on the page. To enable page methods, you also need to add EnablePageMethods="true" to the ScriptManager like this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Server side code (VB):
<Services.WebMethod()> Public Shared Function GetPreviewImages() As String
Dim lPreviewImages As String = HttpContext.Current.Session("mPreviewImages")
If lPreviewImages IsNot Nothing Then
Return lPreviewImages
Else
Return ""
End If
End Function
Client side code:
//Declare the return methods:
function GetPreviewImages_Success(result, userContext, methodName) {
alert(result);
}
function GetPreviewImages_Failed(error, userContext, methodName) {
var errorMessage = 'Error in map server method ' + methodName ;
if(error !== null) errorMessage += '\n' + error.get_message();
alert(errorMessage);
}
// Call the page method:
PageMethods.GetPreviewImages(GetPreviewImages_Success, GetPreviewImages_Failed);
See also example in C#, which also includes how parameters work in the web method.
Related
suppose i have many heavy control is on the page. as for example i have three gridview populated on the page and one gridview & button is inside the updatepanel. from this scenario we can understand that there will be huge viewstate on the page. so i want to know that if i click on button inside the updatepanel then all the viewstate will be submitted to server during partial postback or not. if huge viewstate submit to server and comes back to client then what is the advantage of partial postback because response time will be slower. so tell me how could i tune up the code that only required things will only submit to server. discuss the partial postback concept in detail as a result we can take right action to have good performance. thanks.
+1 to geek!
If you are concerned about the performance of your page(s), I would also recommend using ListView instead of GridView:
https://web.archive.org/web/20211020153238/https://www.4guysfromrolla.com/articles/122607-1.aspx
http://weblogs.asp.net/scottgu/archive/2007/08/10/the-asp-listview-control-part-1-building-a-product-listing-page-with-clean-css-ui.aspx
http://basgun.wordpress.com/2007/12/27/listview-control-in-aspnet-35-1/
http://basgun.wordpress.com/2007/12/28/listview-control-in-aspnet-35-2/
http://basgun.wordpress.com/2007/12/29/listview-control-in-aspnet-35-3/
http://basgun.wordpress.com/2007/12/30/listview-control-in-aspnet-35-4/
You can also visit Matt Berseth's blog to see how ListView can get very handy (and neat) for different types of development scenarios:
http://mattberseth.com/blog/listview/
it's important to keep in mind that an UpdatePanel's partial postback invokes a full page life-cycle on every single async request.
Please check out following links for pros and cons of the update panel.
Why ASP.NET AJAX UpdatePanels are dangerous
Why you should not place your whole site in an UpdatePanel
Are you making these 3 common ASP.NET AJAX mistakes?
so i want to know that if i click on button inside the updatepanel then all the viewstate will be submitted to server during partial postback or not
Yes, it will. The entire page's view state is transmitted (in its entirety) to the server on partial page postback, and the new view state is sent back (in its entirety) from the server back to the client on response.
I'd suggest you use a tool like Fiddler to examine the HTTP traffic between the browser and your server when making a partial page postback. This article provides an overview of using Fiddler - Troubleshooting Website Problems by Examining the HTTP Traffic.
In short, the UpdatePanel is meant as a quick and dirty way to get partial page postbacks without having to worry about client-side script or writing logic on the server to specifically handle a partial page postback. Such simplicity comes at a cost, as you've discovered. :-)
For more control over the content that is sent to and from the server on a partial page postback you need to write client-side script and create server-side methods or services to handle the Ajax requests. These articles offer various techniques for providing such functionality:
Accessing JSON Data From an ASP.NET Page Using jQuery
Using Ajax Web Services, Script References, and jQuery
Using WCF Services with jQuery and the ASP.NET Ajax Library
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
I have mini modules(think iGoogle) that are currently loaded via the page calling LoadUserControl method and loading that control into PlaceHolders. I need to switch that implementation to loading the controls through a jQuery AJAX request. The problem currently lies in the fact that when I perform an AJAX Get, I can load the modules by appending them to the content but none of the functionality that would otherwise be working on a normal loaded control is there. For example, when I select a different option on the a DDL the page refreshes and nothing changes. I suspect because it is because the methods aren't being tied in when I perform a load through AJAX. Additionally when I use this method my flash content is not being loaded.
Am I doing something wrong here, or is there a better solution ?
$.ajax({
url: '/modules/UserModules.aspx?CID=12345',
type: "GET",
dataType: "html",
success: function(data) {
$('#column1').append($(data).find('div#lm li'));
$('#column2').append($(data).find('div#cm li'));
$('#column3').append($(data).find('div#rm li'));
alert('Load was performed.');
}
});
When you post back to the server, the server doesn't know about your user control because it was added to the page dynamically. Actually, you render the UC HTML, then add part of the rendered HTML to your page.
I would recommend steering clear of posting back to the server and using jQuery to retrieve any data using a Page Method or web method when you make a selection using your DDL.
I'm not sure I see the utility in using a UC for this. There are a number of ways to do this sort of thing. Like Jamie said, you can have a plain .aspx page that uses web methods. An asmx page. You can also not use web methods and just do as you would with php or classic ASP by writing your string results directly and processing them (shouldn't be your first choice though!).
But the most important thing you can take from this is debugging. Put a break point in your UC code to track server side. Use Firebug: open it, choose console and watch to see if your GET requests are actually doing what they need to. These days, you rarely need an alert to debug.
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.
I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page.
I don't need to do any DOM updates before, after, or during the callbacks.
I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.
What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.
I really just want to be able to call a single method on the page, nothing else.
Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.
UPDATE
I've decided to accept DanP's answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does.
What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?
The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible?
If you don't want to create a blank page, you could call a IHttpHandler (ashx) file:
public class RSSHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
context.Response.ContentType = "text/xml";
string sXml = BuildXMLString(); //not showing this function,
//but it creates the XML string
context.Response.Write( sXml );
}
public bool IsReusable
{
get { return true; }
}
}
You should use ASP.Net Callbacks which were introduced in Asp.Net 2.0. Here is an article that should get you set to go:
Implementing Client Callbacks Programmatically Without Postbacks in ASP.NET Web Pages
Edit: Also look at this:
ICallback & JSON Based JavaScript Serialization
What do you think would be the best method of transferring data to the IHttpHandler? Should I added variables to the query string or POST the data I need to send? The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly
Considering the callback is buried in the client code, it would take someone with equal determination to get either the querystring or the POST request. IE, if they have firebug, your equally screwed.
So, in that case, do whatever is easiest to you (Hint: I'd just use the querystring).
To handle repeating requests/direct access, I'd generate a key that is sent with each request. Perhaps a hash of the current time (Fuzzy, I'd go down to minutes, but not seconds due to network latency) + the client IP.
Then in the HTTPHandler, perform the same hash, and only run if they match.
You are not just restricted to ASP.NET AJAX but can use any 3rd party library like jQuery, YUI etc to do the same thing. You can then just make a request to a blank page on your site which should return the headers that contain the cookies.
My vote is with the HTTPHandler suggestion as well. I utilize this often. Because it does not invoke an instance of the page class, it is very lightweight.
All of the ASP.NET AJAX framework tricks actually instantiate and create the entire page again on the backend per call, so they are huge resource hogs.
Hence, my typical style of XmlHttpRequest back to a HttpHandler.
Since you are using only ASP.NET 2.0 I would recommend AjaxPro will which create the .ashx file. All you have to do is to pull the AjaxPro.dll into your web site. I developed an entire application with AjaxPro and found it worked very well. It uses serialization to pass objects back and forth.
This is just a sample on how to simply use it.
namespace MyDemo
{
public class Default
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));
}
[AjaxPro.AjaxMethod]
public DateTime GetServerTime()
{
return DateTime.Now;
}
}
}
To call it via JavaScript it is as simple as
function getServerTime()
{
MyDemo._Default.GetServerTime(getServerTime_callback); // asynchronous call
}
// This method will be called after the method has been executed
// and the result has been sent to the client.
function getServerTime_callback(res)
{
alert(res.value);
}
EDIT
You also have to add
To the config. AjaxPro also works well side by side with APS.NET Ajax and you can pass C# objects from Client to Sever if the class is marked as [Serializable]
Just to offer a different perspective, you could also use a PageMethod on your main page. Dave Ward has a nice post that illustrates this. Essentially you use jQuery ajax post to call the method, as illustrated in Dave's post:
$.ajax({
type: "POST",
url: "Default.aspx/GetFeedburnerItems",
// Pass the "Count" parameter, via JSON object.
data: "{'Count':'7'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
BuildTable(msg.d);
}
});
No need for Asp.Net Ajax extensions at all.
You should use a web service (.asmx). With Microsoft's ASP.NET AJAX you can even auto-generate the stubs.
You can also use WebMethods which are built into the asp.net ajax library. You simply create a static method on the page's codebehind and call that from your Ajax.
There's a pretty basic example of how to do it here