Popular Dropdownlist with JSON

Asked

Viewed 691 times

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, there are no vendors that JSON returns, and yes, it returns 3 records, already debugged. What can be?

2 answers

2

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

I just inserted it into my method, into the controller:

myContext.Configuration.ProxyCreationEnabled = false;

0

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

$(result).each(function (índex, value) { 
   ddl.append( $('<option />', 
     { value: value.Id }).html(value.Name) ); 
});
  • I switched here, but still not returning to me the records.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.