Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Friday 8 March 2013

Page Method Or Web Method In ASP.Net | Jquery Ajax() Call

In this article, I’ll talk about what are page methods, and also with the help of an example, we will see how to retrieve data from the database by using Jquery Ajax() method and populate it in a dynamically created HTML table.

What Are Web Methods?

Page Methods or Web Methods are very efficient because neither they need an instance of page nor they require view state to be posted. So point to be noted is that the page method must be static i.e. (static methods can be called without a class instance) because they are independent of page class. Page methods are equivalent to web services.

Example:

In this example, I am going to make a web method "GetPerson()" which will get records from a SQL server table(Person) using Jquery Ajax() method. I am using Microsoft SQL Server. Let's create a table named person and insert some records in it.

sql-person-table


Below is the record in the table.



Jquery Ajax() method allows us to call ASP.NET server-side methods from the client-side without any page refresh or postback.

Jquery code for Default.aspx page :

 
 <script type="text/javascript">
  function retrieveData(){
    // Here goes the ajax method
    $.ajax({
    	type:"POST",
    	url:"Default.aspx/GetRecords ",
    	data:"{}",
    	contentType:"application/json; charset=utf-8",
    	dataType:"json",
    	success:onSuccessData
     });
   
 function onSuccessData(msg){
  var data=msg.d;
  var table="";// dynamically table is created here.
  table+="<table border='1' align='center'>"
  table+="<tr><th>Person ID</th><th>Person Name</th>";
  table+="<th>Person Address</th></tr>";
        if(data.length>0){
        
        for(var i=0; i<data.length;i++){
        	table+="<tr><td>"+data[i].PersonID+"</td>";
        	table+="<td>"+data[i].PersonName+"</td>";
        	table+="<td>"+data[i].PersonAddress+"</td></tr>";
     
        }
       }
        else{
	table+="<tr><td colspan='3' >No Record(s) Found</td></tr>";
        }
         table+="</table>";
        $("#divTable").html(table);
       
        }
    }
    <script>

C# code for Default.aspx.cs page :

First, add necessary namespaces on the page otherwise you will see red squiggly lines under your code.  The method is declared static and writes the keyword [WebMethod] on the top left before starting the method otherwise if you don't write this keyword the client-side Jquery Ajax() method will unable to call this method on the server-side. 

// For database connectivity
using System.Data.SqlClient;
// For defining web method.
using System.Web.Services;
//Because we use List.
using System.Collections.Generic;


    [WebMethod]
    public static List<Person> GetRecords()
    {

        List<Person> p = new List<Person>();
        // Datbase connection string.
        SqlConnection con = 
        new 
        SqlConnection
        (ConfigurationManager.ConnectionStrings["Strng"].ConnectionString);
        // if you want to use stored procedure instead of query
        // then un-comment the below two lines.
        /*  SqlCommand cmd = new SqlCommand("show_Record",con); 
        //"show_Record " is the name of stored procedure.
           cmd.CommandType = CommandType.StoredProcedure;*/

        SqlCommand cmd = new SqlCommand("select * from person", con);
        cmd.CommandType = CommandType.Text;

        con.Open();

        SqlDataReader dr = cmd.ExecuteReader();
        // check if data reader object reads the data and has some rows.
        if (dr.HasRows)
        {
            // read the data untill 0
            while (dr.Read())
            {
                Person per = new Person();
                per.PersonID = Convert.ToInt32(dr["Person_ID"]);
                per.PersonName = dr["Person_Name"].ToString();
                per.PersonAddress = dr["Person_Address"].ToString();
                p.Add(per);

            }
            dr.Close();
            con.Close();


        }
        return p;


    }
}
 



	public class Person
	{

  	  public int PersonID { get; set; }
  	  public string PersonName { get; set; }
  	  public string PersonAddress { get; set; }

	}
  

And here is the final result on your browser screen:

final-result-of-page-method

3 comments:

  1. I need you help this binds first row in table and not bind other rows on in table please check

    ReplyDelete
    Replies
    1. It has been corrected table tag should be end at last after for loop.

      Delete
  2. I read this article. I think You put a lot of effort to create this article. I appreciate your work. click here

    ReplyDelete

Please do not enter spam links.