Anna Marie Rapa
Anna Marie Rapa

Reputation: 119

Passing a string from code behind to ajax

I am accessing a method on the server side. The only problem is that I don't have alot of experience in AJAx. I am unable to retrieve the returned string in the ajax from the .cs method

$.ajax({
  type: 'GET',
  url: '/frmGpsMap.aspx?name=load',
  dataType: 'text',
  success: function(data) {
    alert(data.d);
  }
});
 protected void Page_Load(object sender, EventArgs e)
        {
            string crrName = Request.QueryString["name"];
            if (!String.IsNullOrEmpty(crrName))
            {
                if (crrName.ToLower().Equals("load"))
                {
                 string fh=   loadKMLFileToString();
                 hdnUsername.Value = fh;
                }
            }
        }

        public string loadKMLFileToString()
        {
            return "hello world";
        }

The alert is returning the html of the page. I want to display the "Hello World" string

Upvotes: 1

Views: 2123

Answers (2)

Daniel Oliveira
Daniel Oliveira

Reputation: 1141

I think you can decorate your cs method with the WebMethod attribute and call it directly from ajax. Like this:

 $.ajax({
  ...
  url: '/frmGpsMap.aspx?loadKMLFileToString',
  ...
});


  [System.Web.Services.WebMethod]
    public string loadKMLFileToString()
    {
        return "hello world";
    }

Cheers! =)

Upvotes: 2

chrana
chrana

Reputation: 209

To get the code behind method to work with ajax you need to use System.Web.Services.WebMethod. By default you need to use POST unless you specify HTTP GET attribute in code behind

[System.Web.Services.WebMethod]
public static string LoadKMLFileToString()
{
    return "Hello World";
}

Here is the ajax method for call

$.ajax({
        type: "POST",
        url: "frmGpsMap.aspx/LoadKMLFileToString",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            alert(response.d),
        failure: function(response) {
            alert(response.d);
        }
    });

I hope it helps. More examples: http://weblogs.asp.net/karan/calling-server-side-method-using-jquery-ajax

Upvotes: 4

Related Questions