【问题标题】:Fill DropDownList with Json用 Json 填充 DropDownList
【发布时间】:2015-06-11 11:52:28
【问题描述】:

ActionResult Create():

ViewBag.Quantity = new SelectList(new List<SelectListItem>(), "Value", "Text");

查看:

@Html.DropDownList("Quantity", null, htmlAttributes: new { @class = "form-control" })

jQuery:

var $quantity = $('#ProdQuantity');
function GetQuantity() {
    $.getJSON('/Sales/GetQuantity?Id=' + $products.val())
    .done(function (result) {
         $quantity.empty().append($('<option />', { value: '', text: $select, selected: true, disabled: true }));
        $(result).each(function () {
            $quantity.append(
            $('<option />', {
                value: this.Value
            }).html(this.Text))
        });
    })
    .fail(function (jqXHR) { console.log(jqXHR.responseText) });
};

ActionResult GetQuantity():

public ActionResult GetQuantity(int Id)
    {         
        Product product = db.Products.Find(Id);

        var quantity = new List<SelectListItem>();

        for (var i = 1; i <= product.Quantity; i++)
        {
            quantity.Add(new SelectListItem()
            {
                Text = i.ToString(),
                Value = i.ToString()
            }
            );
        }

        return Json(quantity, JsonRequestBehavior.AllowGet);
    }

嗯,我只是想在更改产品后填写产品可用数量的下拉列表。不知道怎么回事。。

我查看了body响应,结果如下:

[{"Disabled":false,"Group":null,"Selected":false,"Text":"1","Value":"1"},{"Disabled":false,"Group":null,"Selected":false,"Text":"2","Value":"2"}]

正如我所料,但它没有填充下拉菜单。

响应头:

Answer HTTP/1.1 304 Not Modified

我有很多语法相同的脚本,它们都运行良好。

【问题讨论】:

标签: c# jquery json


【解决方案1】:

首先需要添加编码如下

    return Json(quantity,"text/json", JsonRequestBehavior.AllowGet);

并像这样编辑您的 jQuery 代码

var $quantity = $('#Quantity');
function GetQuantity() {
    $.getJSON('/Sales/GetQuantity?Id=' + $products.val())
    .done(function (result) {
         var items=[];

         $quantity.empty()
            .append($('<option />', 
                   { value: '', 
                     text:     "select", 
                     selected: true, 
                     disabled: true }));

        $.each(result,function (index,item) {
           items.push('<option value="'+item.Value+'">'+item.Text+'</option>');
        });
         $quantity.html(items.join(''));
    })
    .fail(function (jqXHR) { console.log(jqXHR.responseText) });
};

【讨论】:

  • +1 向我展示了另一种方法(它似乎有效,我没有测试过),但问题出在$('#ProdQuantity').. 我没有注意到我有那个老身份证了。谢谢。
【解决方案2】:

如果您想更新此下拉菜单:

@Html.DropDownList("Quantity", null, htmlAttributes: new { @class = "form-control" })

id="Quantity" 不是ProdQuantity

所以$('#ProdQuantity'); 应该是$('#Quantity');

像这样更新下拉列表:

 var targetDropdown = $("#Quantity");


$.ajax({
        type: 'GET',
        url: '',
        contentType: 'application/json'
        success: function (response) {
            targetDropdown.empty();

    $.each(response, function (val, item) {
    targetDropdown.append($("<option></option>").val(item.Value).html(item.Text));
    });
    }

【讨论】:

  • 我怎么会这么愚蠢/盲目。在我改变一切之前,那个变量有另一个 ID,当问题出在变量 -.- 时,我尝试了 10 种方法来做到这一点。无论如何,我发布的那个功能是正确的,它现在可以工作了,我会接受你的回答,因为你发现了问题。谢谢大佬。
【解决方案3】:

使用Json.Net

var response =  JsonConvert.DeserializeObject<Response>(json);
foreach(var item in response.datas)
{
    DropDownList1.Items.Add(new ListItem(item.Value, item.Key));
}

public class Response
{
    public bool state;
    public Dictionary<string, string> datas;
}

这也可能是个问题:

public ActionResult GetQuantity(int Id) {
产品product = db.Products.Find(Id);

    var quantity = new List<SelectListItem>();

    for (var i = 1; i <= product.Quantity; i++)
    {
        quantity.Add(new SelectListItem()
        {
            Text = i.ToString(),
            Value = i.ToString()
        }
        ); <-----To what does this belong?
    }

    return Json(quantity, JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    相关资源
    最近更新 更多