0

All,

How can I bind the array of drop down list items returned from the web service method to the ddlSubCategory asp.net server control? Here is my code. See comments in the jquery OnSuccess method:

<script type="text/javascript">
    $(document).ready(function () {
        $('#<%=ddlParentCategory.ClientID%>').change(function () {
            var selectedParentCategory = getParentCategorySelectedValue();
var params=  []; 
params[id] = selectedParentCategory;  

          $.ajax({
                              type: "POST",
                              url: "MyWebService.asmx/GetSubCategoryItems",
                              data: params,               
                              contentType: "application/json; charset=utf-8",               
                              dataType: "json",               
                              success: OnSuccess,               
                              error: OnError
           });
                      });

    function OnSuccess(data, status) {
;// need to populate ddlSubCategory <asp:DropDownList on UI now
;// using returned array of drop down list items from the web service
    }        

    function OnError(request, status, error) {
                   alert(request.statusText);
    }

        function getParentCategorySelectedValue() {
            var SelectedVal = $('#<%=ddlParentCategory.ClientID %>').val();
            return SelectedVal;
        }

   });    
</script>

Here is my web service web method returning the array of list items:

[WebMethod]
        public ListItem []  GetSubCategoryItems(int id)
        {
            using (var dc = MyDataContext.Open())
            {
                return dc.SubCategory
                    .OrderBy(sc => sc.Name)
                    .Select(sc => new ListItem()
                                     {
                                         Value = sc.ID.ToString(),
                                         Text = sc.Name
                                     })
                    .Prepend(new ListItem() {Value = "", Text = "Please Select"})
                    .ToArray();
            }
        }

thanks for any help!

Frekster
  • 1,138
  • 1
  • 14
  • 32
  • Changing the contents of a dropdown list server control is a sure-fire method to generating request validation errors. Either turn off request validation (I think you can do this on control basis) or use the html select server control. – Simon Halsey Jul 04 '12 at 13:18

2 Answers2

1

You can try something like this:

function OnSuccess(data, status) {
    // create a variable to the array
    var list = data;
    //get your combobox
    var $select = $('#<%=ddlParentCategory.ClientID %>'); 
    //check if it contains some items
    if (list.length > 0) {
        $select.empty().append('<option value="0">Please select...</option>');
        $.each(list, function () {
            $select.append($("<option></option>").val(this['Value']).html(this['Text']));
        });
        // $select.val(valueselected); //if you want to select a value... add this line
    }
    else //empty result from array
        $select.empty().append('<option selected="selected" value="0">Empty...<option>');
}

I don't know hwo you are returning your array from the web method in the web service, but you have to consider this items to get it work:

  • your web service has to be accessible by scripts, so add [System.Web.Script.Services.ScriptService] attribute on your web service class.
  • make your web service method to become accessible via get (try to access directly from the browser). You can do something like this on the web.config file.
  • return on the json format, look at this link
  • be sure that your parameter data on the OnSuccess function, has no properties with the array, e.g., data.items
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
  • Hi felipeoriani and thanks for the code! The data parameter is coming into the OnSuccess function as undefined. In the web service method, the array of list items has a count of 8, it is returned to the OnSuccess function and is seen as undefined in jquery. How can I get the return type of my web service method to show up in jquery as an array or at least as a defined object? Thanks for any help! – Frekster Jul 04 '12 at 15:48
  • Hi @Frekster, take a look at my edits on my awser. It would be nice if you share your code of the web method. :) – Felipe Oriani Jul 04 '12 at 16:03
  • Hi again felipeoriani. I posted my web service method in the original question/post :). It is returning an array of ListItem objects. I actually got this to work now using your code with a minor adjustment. I had to use var list = data.d; the .d property is what asp.net wraps the json response in when returning it from the asmx web method. [see this link](http://encosia.com/a-breaking-change-between-versions-of-aspnet-ajax/). – Frekster Jul 04 '12 at 17:00
  • Yes, I'm not sure but I think it by default of asp.net web services, using .d property to get the results with json response :) – Felipe Oriani Jul 04 '12 at 17:06
1
function OnSuccess(data, status) {
   var array = JSON.parse(data).toArray(); 
   var ddl = $('#<%=ddlParentCategory.ClientID %>');
   for (var item = 0; item < array.length; item++)
   {
      $(ddl).append($("<option>" + item + "</option>"))
   }
}

More can be found here : http://www.dotnetfunda.com/articles/article999-dynamically-adding-an-item-in-a-dropdownlist-control.aspx Good luck.

Max
  • 417
  • 7
  • 21