简体   繁体   中英

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

            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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM