0

ActionResult Create():

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

View:

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

Well I'm just trying to fill a dropdownlist of available quantities of a product, after change the product. I don't know what's wrong..

I looked at the body response, here is the result:

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

As I expected, but it isn't filling the dropdown.

The response header:

Answer HTTP/1.1 304 Not Modified

I have lots of scripts with the same syntax, and they all are working fine.

developer033
  • 24,267
  • 8
  • 82
  • 108
  • In your jQuery I dont think `append()` accepts an object as an argument. Your result looks like its returning an array of objects which is fine but you want HTML elements. Have a look here - http://stackoverflow.com/questions/815103/jquery-best-practice-to-populate-drop-down and here - http://stackoverflow.com/questions/8090457/populating-select-option-dynamically-with-jquery they might give you an idea. You also seem to be self closing you option tags which you shouldnt be doing -http://stackoverflow.com/questions/3558119/are-self-closing-tags-valid-in-html5 – Craicerjack Jun 11 '15 at 12:01

3 Answers3

1

First of all, you need to add encoding as follows

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

and edit your jQuery code as this

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) });
};
Bellash
  • 7,560
  • 6
  • 53
  • 86
  • 1
    +1 for show me another way to do that (it seems work, I haven't tested), but the problem was just in the `$('#ProdQuantity')`.. I hadn't noticed I had that old Id yet. Thanks. – developer033 Jun 11 '15 at 14:03
0

Using 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;
}

This could be a also be a problem:

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()
        }
        ); <-----To what does this belong?
    }

    return Json(quantity, JsonRequestBehavior.AllowGet);
}
The_Monster
  • 494
  • 2
  • 7
  • 28
0

IF you want to update this dropDown:

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

The id="Quantity" not ProdQuantity

so $('#ProdQuantity'); should be $('#Quantity');

Update a Dropdown like this:

 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));
    });
    }
Dawood Awan
  • 7,051
  • 10
  • 56
  • 119
  • How could I be so stupid/blind.. That variable had another Id before I change everything, I tried like 10 ways of do that, when the problem was in the variable -.-. Anyway, that function I posted is correct, it's working now, I'll accept ur answer because you found the problem. Thanks man. – developer033 Jun 11 '15 at 13:57