开发者

Updating a Drop down list with Jquery from JSON

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()});
            }

    开发者_Go百科        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?


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:

  • DOM select object's .add()
  • jQuery object's .add()


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜