Friday, July 29, 2011

Call Server Side Method using ajax JQuery in ASP .Net

When I have started work on ajax. I used to passed parameters in the url while calling server side method through ajax call. But problem was that when we send value with Hash(#). It was not sending whole value to server side.It was sending only value before hash(#). Than I have found another way to send parameter to sever side.We can directly call server side method and pass parameter through ajax call.

Write this function on client side.

function SendServer()

// var sVal = $("#txtName").val();

var sVal = "Red";

type: "POST",
url: "Customer.aspx/GetValue",
data: "{param1: " + "'" + sVal + "'" + " }",
//data: "{'param1': 1}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)

// $('#Rslt').text(msg);
// $('#Rslt').text("Some error has been occurred.");

And on server side define a static method with WebMethod attribute. Add a name space System.Web.Services

public static string GetValue(string param1)
return "Call Server Side method through ajax call and pass parameter :" + param1;

One thing that you have to remember parameter name should be same on both side.Just like the above example I have used param1 both side.

You can download the sample code from here.

No comments: