使用JSON中的Jquery更新下拉列表 [英] Updating a Drop down list with Jquery from JSON

查看:51
本文介绍了使用JSON中的Jquery更新下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,我需要使用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);
        }

这是我为各种各样的javascript收集的内容来源:

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

您是否尝试创建选项然后将其添加到选择?如果是这样,就这样做,使用 .append()

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

selectList.append(option);

有了这个,我还在假设新选项(optionData.Text, optionData.Value); 正在创建一个新的选项,在jQuery中它就像这个 var option = $(' < option>')。text(optionData.Text).val(optionData.Value);

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

添加了注释.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()`.

解决方法就是这样,

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

之间的差异:

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

这篇关于使用JSON中的Jquery更新下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆