views:

31

answers:

2

I have a list that I need to fill using a JSON collection of object. Here is what my action is returning:

public ActionResult GetProductCategories()
        {
            var categories = _entities.ProductCategories.ToList();

            var result = new List<SelectListItem>();

            foreach (var category in categories)
            {
                result.Add(new SelectListItem {Text = category.CategoryName, Value = category.CategoryId.ToString()});
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

This is what I've come up with for my javascript, gathered from various sources:

function loadCategories() {
            $.getJSON("/Admin/Product/GetProductCategories", null, function (data) {
                var selectList = $("#subCategories");

                $.each(data, function(index, optionData)
                {
                    var option = new Option(optionData.Text, optionData.Value);
                    selectList.add(option, null);
                });                
            });
        }

But it doesn't appear to be working, and isn't giving any errors. Whats the best practice for this sort of thing?

+1  A: 

JQuery fails silently if it doesn't like the JSON data coming back from the server. Point your browser at /Admin/Product/GetProductCategories and look at the result. Make sure it doesn't have any html tags and make sure there are double quotes around the key names.

MattSmith
Yep, the data coming back is valid - it seems to be how I'm adding to the selectList.
Gallen
+2  A: 

I was wondering what are you trying to achieve in this next lines of codes,

var option = new Option(optionData.Text, optionData.Value);
selectList.add(option, null);

are you trying to create an option then add it on select? if so, do it like this, use .append()

selectList.append(option);

with that, I'm still assuming new Option(optionData.Text, optionData.Value); is creating a new option, in jQuery it would be like this var option = $('<option>').text(optionData.Text).val(optionData.Value);


added notes for .add(),

var selectList = $("#subCategories"); // creates jQuery object selectList.
selectList.add(option, null); // selectList is jQuery object,
                              // so when you call .add(), you're calling jQuery's `add()`.

a workaround is this,

selectList[0].add(option, null); // you can use [0] to convert it into DOM object.

difference between:

Reigel
+1 - The `.add()` is certainly a problem, good catch...I kept seeing `.options.add()` but that's not what he's calling here.
Nick Craver
Woot! This worked. Thanks everyone!
Gallen