How do I Populate a DropDownList with Results from a Web Service Method?
I have an ASP.NET 3.5 webforms application that needs to interact with an ASP.NET web service. The web service provides a list of valid values to be populated into a dropdownlist. Is it advisable to do this on the client side or the server side? If done on the server side, how do I defin开发者_JS百科e a data source set to my asmx web service? If done on the client side, please suggest a good JQuery widget.
Thanks much for your help!!
Opts I'd define a WCF service that used one of the built in collection Data contracts to render a list in JSON:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class optionsservice
{
// Return a dynamic list of the options
[WebInvoke(UriTemplate = "/getOptions?type={type}", Method = "GET", ResponseFormat = WebMessageFormatJson)]
public SelectOptions getOptions(string filter = "")
{
SelectOptions returnOptions = new SelectOptions();
//get your datatable here.
foreach (DataRow r in tbl.Rows)
{
returnOptions.Add((string)r["id"], (string)r["value"]);
}
return returnOptions;
}
[CollectionDataContract(Name = "collection",
KeyName = "id",
ValueName = "value",
Namespace = "")]
public class SelectOptions : Dictionary<string, string> { }
}
You could also cast the datatable to a list but this was the only example code I had on-hand
Here is how you would load the box into jQuery:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(function(){
$("select#ctlSelect").change(function(){
$.getJSON("/select.php",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].id + '">' + j[i]value + '</option>';
}
$("select#ctlSelect").html(options);
})
})
})
</script>
精彩评论