In this article we will discuss how to get JSON data from webservice and bind it to dropdownlist. I have used jquery $.ajax to achieve it. It can be used with html page only without any aspx page
Let's see how we can do this.
Step 1: Create a webservice JsonWebService.asmx and write a method named GetCarManufacturer(). Scriptmethod with ResponseFormat and UseHttpGet needs to be added above the GetCarManufacturer method to return Json data. UseHttpGet should be set to true to avoid JSON hijacking. Read this article by Scott Guthrie JSON Hijacking. The complete webservice should be like below. I have created a car class with manufcturerName and manufacturerid.
public class JsonWebService : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet=true)] public List<Cars> GetCarManufacturer() { return PrepareCarData(); }
public List<Cars> PrepareCarData() { List<Cars> objCars = new List<Cars> { new Cars{manufcturerName = "Merc", manufacturerid= 1} , new Cars{manufcturerName = "BMW", manufacturerid= 2} , new Cars{manufcturerName = "Audi", manufacturerid= 3} , new Cars{manufcturerName = "Suzuki", manufacturerid= 4} , new Cars{manufcturerName = "GM", manufacturerid= 5} , new Cars{manufcturerName = "Toyoto", manufacturerid= 6 } , }; return objCars; } }
public class Cars { public string manufcturerName; public int manufacturerid; }
Step 2: Add jquery-1.4.2.min.js on the page head and a html select control and a div to show error.
<html> <head> <title></title> <script src="jquery-1.4.2.min.js" type="text/javascript"></script> </head>
<body> <select id="carmanufacturer"> </select> <div id="errMessage"></div> </body> </html>
Step 3: Add below javascript in the html page. Type "GET" and contentType "application/json; charset=utf-8" needs to be specified while requesting to because webservie method has signature of Get and webservice method returns JSON data.
<script language="javascript" type="text/javascript"> $(document).ready(function() { $.ajax({ type: "GET", url: "JsonWebService.asmx/GetCarManufacturer", contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { var carManufacturer = response.d; for (var i = 0; i < carManufacturer.length; i++) { var selectOption = $(document.createElement('option')); $('#carmanufacturer').append(selectOption.val(carManufacturer[i].manufacturerid).html(carManufacturer[i].manufcturerName) ); } }, failure: function(errMsg) { $('#errMessage').text(errMsg); } }); }); </script>
Live Demo
This ends the article of calling webserive using jquery.
|