Geeks With Blogs
Moez Mousavi

These days people would expect a web page with absolute no post back rather than asking for it. Utilising Microsoft update panel is good but it is not always helpful. I recently come across a page and tried to do a quick fix using update panel. The result was randomly throwing error...

The best practice would be using JQuery. There is a very simple way to implement a nice, clean solution which I bet you would prefer it to the Microsoft Update panel. My favorite is $.ajax() although there are more JQuery functions like $.getJson().

Lets walkthrough doing an Ajax call:

Step 1: Make a web service

You would need to write all of your database talk in some methods in a web service. You could pass parameters and return Json object. Webservice should be decorated with [ScriptService and methods should with  [ScriptMethod]

Step 2:

Add Script manager, reference your web service:

<asp:ScriptManager id="scriptManager" runat="server">
    <Services>
        <asp:ServiceReference  Path="/MyWebservice.asmx" />
    </Services>
</asp:ScriptManager>

you might leave the script manager in your master page and reference the JQuery library at the same place.

Step 3: Call your web service method using $.ajax():

function MyWebServiceMethod(parameter1, parameter2) {

 

    $.ajax({

        type: "POST",

        url: "/MyWebService.asmx/WebMethod",

        data: "{'parameter1':'" + parameter1 + "','parameter2':'" + parameter2+ "'}",

        contentType: "application/json; charset=utf-8",

        dataType: "json",

        success: function (response) {

            if (response.d == 0) {

 

               //Do something 

            }

        },

        failure: function (msg) {

            alert("There is an error...");

        }

    });

}

 

response.d == 0 means it is working properly. However response itself could be an object (Json object) which is returned by the webservice. So you can have for example response.Name, response.Price, etc.

 

 

 

 

 

Posted on Saturday, September 24, 2011 1:50 AM JavaScript , JQuery , C# , ASP.NET | Back to top

Copyright © MoezMousavi | Powered by: GeeksWithBlogs.net