Calling a webservice via Javascript

Posted by jeroenb on Geeks with Blogs See other posts from Geeks with Blogs or by jeroenb
Published on Sat, 29 Jan 2011 07:35:52 GMT Indexed on 2011/01/29 23:26 UTC
Read the original article Hit count: 192

Filed under:

If you want to consume a webservice, it's not allways necessary to do a postback.
It's even not that hard!

1. Webservice

You have to add the scriptservice attribute to the webservice.

[System.Web.Script.Services.ScriptService]
public class PersonsInCompany : System.Web.Services.WebService {


Create a WebMethod

    [WebMethod]
public Person GetPersonByFirstName(string name)
{
List<Person> personSelect = persons.Where(p => p.FirstName.ToLower().StartsWith(name.ToLower())).ToList();
if (personSelect.Count > 0)
return personSelect.First();
else
return null;
}


2. webpage


Add reference to your service to your scriptmanager

<script type="text/javascript">
function GetPersonInCompany() {
var val = document.getElementById("MainContent_TextBoxPersonName");
PersonsInCompany.GetPersonByFirstName(val.value, FinishCallback);
}

function FinishCallback(result) {
document.getElementById("MainContent_LabelFirstName").innerHTML = result.FirstName;
document.getElementById("MainContent_LabelName").innerHTML = result.Name;
document.getElementById("MainContent_LabelAge").innerHTML = result.Age;
document.getElementById("MainContent_LabelCompany").innerHTML = result.Company;
}
</script>


Add some javascript, where you first call your webservice.
Classname.Webmethod = PersonsInCompany.GetPersonByFirstName
Add a callback to catch the result from the webservice. And use the result to update your page.

<script type="text/javascript">
function GetPersonInCompany() {
var val = document.getElementById("MainContent_TextBoxPersonName");
PersonsInCompany.GetPersonByFirstName(val.value, FinishCallback);
}

function FinishCallback(result) {
document.getElementById("MainContent_LabelFirstName").innerHTML = result.FirstName;
document.getElementById("MainContent_LabelName").innerHTML = result.Name;
document.getElementById("MainContent_LabelAge").innerHTML = result.Age;
document.getElementById("MainContent_LabelCompany").innerHTML = result.Company;
}
</script>

 
If you have any question, feel free to contact me!

You can download the code here.

© Geeks with Blogs or respective owner