Popular DropDownList with JSON

1

- Controller -

 [WebMethod]
 public ActionResult GetSellers()
 {
    List<Seller> sellers = db.Sellers.ToList();

    return Json(sellers, JsonRequestBehavior.AllowGet);
 }

- View -

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

- Javascript -

<script type="text/javascript">
    $('#DeptId').change(function () { // DeptId is my another DropDownList
        $.getJSON('/SaleRecords/GetSellers'), null, function (result) { // My path
            var ddl = $('#SellerId'); // My seller DDL
            ddl.empty();
            $('Sellers').show(); // My div (it's display: none)
            $(result).each(function () {
                ddl.append(
                $('<option />', {
                    value: this.Id
                }).html(this.Name)
                );
            });
        };
    });
</script>

Good afternoon,

The problem with this code is that when it is executed, it does not come from the vendors that JSON returns, and yes, it returns 3 records, I have already debugged. What can it be?

    
asked by anonymous 31.05.2015 / 17:38

2 answers

2

I found the answer, for someone I might need in the future, here it is:

I just inserted into my controller method:

myContext.Configuration.ProxyCreationEnabled = false;
    
31.05.2015 / 22:47
0

The each method of jquery receives two parameters: the index of the object in the array and the object of the current iteration:

$(result).each(function (índex, value) { 
   ddl.append( $('<option />', 
     { value: value.Id }).html(value.Name) ); 
});
    
31.05.2015 / 19:42