Go to Comments





3 different ways to implement asp.net ajax


Created: 20/11/2013 08:11:20 p.m.






3 different ways to implement asp.net ajax (On Revision!)

This simple tutorial will show how you can easy add ajax to your asp.net applitacion.

1) First is the most common, just using UpdatePanels

For example i have button in my website and one label, and i want to update the label with some information by clicking button but i dont want to refresh all the site.

This is what i will do to solve this situation:




But the problem is that this code will refresh all the site, so i will add basic ajax functionality to this example:

Modify the code to the fallowing:


<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

    <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:Label ID="lblDate" runat="server" Text=""></asp:Label>
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
        </ContentTemplate>
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
        </Triggers>
    </asp:UpdatePanel>


</asp:Content>


You can see that we have add, Ajax control "UpdatePanel" to our code, and 2 sub tags, first tag is the ContentTemplate, this one contain all the website part that i want to refresh, and the second is basically the trigger
that assign to this UpdatePanel the event of some control that will fire the refresh of this block of code.

Do not forget to add "asp:ScriptManager" to your website because is the "responsable of administrate Ajax functionality".

This is the simplest to add ajax to your application, so there are no much to talk about, just see another tutorials to lern some advanced fetures of this method and you are done. 





2) Second method is using jQuery ajax.

I use this project to implement Ajax:


I have one button that will fire the refresh event, and this one will update DIV with id "hora"

At the beginning we need to add OnClientClick="return false;" to the button, this one will block the postback bocause of the click on this button.

Now this button not going to do anything by clicking it.

This time we need to add the Ajax functionality.
First add jQuery library, in my case i use google libraries, you can find it here:

After this open new script tag and add the fallowing code:


    <script>
        $(document).ready(function () {
            $('#ctl00_ContentPlaceHolder1_btnRefresh').click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default2.aspx/GetDate",
                    contentType: "application/json; charset=utf-8", // Lo que mando
                    dataType: "json", // Lo que recibo
                    success: function (data) {
                        $('#hora').text(data.d);
                    },
                    error: function (XmlHttpError, error, description) {
                        miError = JSON.parse(XmlHttpError.responseText);
                        alert(miError.Message);
                    }
                });
            });
        });
    </script>


It seems to be difficult but its realy not at all.
Basically what we do here is, ataching event "Click" to the button "btnRefresh" and inside this event, call the function that we have add in codebehind this one:


    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }


to make asynchronous call to the server use the jQuery function $.ajax
there are many different properties that you can set in this function, i have add only the required one to make this little example:

url: "Default2.aspx/GetDate", (This is the method (WebMethod) that i want to call)
contentType: (The type of information that i will pass as parameters to my method)
dataType: (The type of information that i will recive from the method,)

Then like in every jquery ajax call i have 2 functions:
if the call complete good, it will use success function, else it will use error.
success function recive the data that my method return, in my case only one string.
So i will update the DIV with the information (date) that my call returned.

You can see that i used "data.d", this is simply a security feature that Microsoft added in ASP.NET 3.5’s version of ASP.NET AJAX (Search in google for more information)

Result:


If you want to pass params to the Method in codebehind you must to add the "data" param in ajax call like this:

    <script>
        $(document).ready(function () {
            $('#ctl00_ContentPlaceHolder1_btnRefresh').click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default2.aspx/GetDate",
                    contentType: "application/json; charset=utf-8", // Lo que mando
                    dataType: "json", // Lo que recibo
                    data: '{param1:"' + $('#ctl00_ContentPlaceHolder1_txtName').val() + '"}',
                    success: function (data) {
                        $('#hora').text(data.d);
                    },
                    error: function (XmlHttpError, error, description) {
                        miError = JSON.parse(XmlHttpError.responseText);
                        alert(miError.Message);
                    }
                });
            });
        });
    </script>

i have added new textbox and get the value from this textbox using jQuery and pass it in JSON format to the WebMethod:

<asp:textbox runat="server" ID="txtName"></asp:textbox>

and in the codebehind method:

    [WebMethod]
    public static string GetDate(string param1)
    {
        return param1 + " : " +DateTime.Now.ToString();
    }

3) Third method is some mix between the two previous
Basicaly like in the second method we need to delacre the STATIC function to call using ajax:


    [WebMethod]
    public static string GetDate()
    {
        return DateTime.Now.ToString();
    }


This method should be static and [WebMethod] attribute


In the html side you dont need to include jQuery:


    <script>
        function ActualizarHora() {
            PageMethods.GetDate(Success, Error);
            return false;
        }

        function Success(arg) {
            document.getElementById('fecha').innerHTML = arg;
        }

        function Error(arg) {
            alert(arg);
        }
    </script>




In this case i use Asp.Net Ajax, so you must use ScriptManager

I have simple DIV where i will puth the returned data from my method.
and a button

In OnClientClick event of the button call your function that will fire ajax call.
In my case i created ActualizarHora.
In ActualizarHora i have my ajax call to the server.
Use PageMethods to access the WebMethods that you created in code-behind
This function accepts the real parameters that you declared on your method and 2 aditional params: OnSuccessFunction and OnFiledFunction, this two you must create yourself

Result:



Download this 3 ways and test yourselft: DOWNLOAD

If you want to add any information or comment somthing add your comment below.




Comments: