yahya kh
yahya kh

Reputation: 751

Retrieve value from webservice called from javascript?

Is it possible to retrieve value or date from calling a webmethode from javascript, here is a sample code:

//This method is in a webservice.asmx file.
[WebMethod]
public List<tbl_City> GetAllCitiesByCountry(int countryID)
{

    return Cities.GetAllCitiesByCountry(CountryID: countryID);
}


<script language="javascript" type="text/javascript">

function fillCities() {
    var dropDownList = document.getElementById('<%=DropDownList_Country.ClientID %>');
    var selectedIndex = dropDownList.selectedIndex;
    var value = dropDownList[selectedIndex].value;

   WebService.GetAllCitiesByCountry(parseInt(value.toString()), onSuccess, null, "");

}

   function onSuccess(result){
      alert(result[0].(PropertyName));
      }

The variable x doesn't retrieve anything and I guess that it produce an error. I have tried to define an array but still it didn't work. Any idea ?

Edit:

The above code have been altered and is now an answer to my question along with the answer below which used JQuery.

Upvotes: 0

Views: 4011

Answers (3)

Zo Has
Zo Has

Reputation: 13038

you can do this easily with JQuery and ASP.NET webmethods Encosia

Upvotes: 1

dipak
dipak

Reputation: 2033

Use Json response with Jquery, Its realy cool and easy.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class CitiService : WebService
{
    [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<tbl_City> GetAllCitiesByCountry(int countryID)
    {
     List<tbl_City> cities = GetCities(countryID);
     JavaScriptSerializer js = new JavaScriptSerializer();
        var jsonObj = js.Serialize(cities);
        Context.Response.Clear();
        Context.Response.Write(jsonObj);
        Context.Response.End();
     }
 }

on ASp.net page

<script language="javascript" type="text/javascript">
 $.ajax({
        url: '<%= ResolveClientUrl("~/CitiService.asmx/GetAllCitiesByCountry") %>',
        dataType: "json",
        data: "{countryID:'100'}",
        success: function (result) {
            alert(result.d.tbl_City.Length) // loop here i.e. foreach to insert in to grid
        }
      });

Upvotes: 2

Samich
Samich

Reputation: 30175

You need to register your web service with ScriptManager and then call it from the client side. Take a look on this tutorial:

Client-Side Web Service Calls with AJAX Extensions

Also you can use web service with jQuery but in this case you need to switch to JSON: Calling ASMX from jQuery

Upvotes: 0

Related Questions