由JSON填充DropDownList

时间:2015-05-31 17:15:28

标签: javascript asp.net json asp.net-mvc-5.2

- 控制器 -

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

    return Json(sellers, JsonRequestBehavior.AllowGet);
}

- 查看 -

@Html.DropDownListFor(x => x.SellerId, new SelectList(Enumerable.Empty<SelectListItem>()))

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

出了什么问题?我在Controller中调试过,而sellersList有3个注册表,但它没有出现在我的视图中,问题是什么?

2 个答案:

答案 0 :(得分:0)

这可能是问题

$.getJSON('/SaleRecords/GetSellers'), null, function (result) // should throw an error

尝试

$.getJSON('/SaleRecords/GetSellers')
.done(function(result) {
        var ddl = $('#SellerId');
        ddl.empty();
        $('Sellers').show();
        $(result).each(function () {
            ddl.append(
            $('<option />', {
                value: this.Id
            }).html(this.Name)
 });
 .fail(function(jqXHR) {console.log(jqXHR.responseText)});

答案 1 :(得分:0)

刚发现错误:我在控制器方法中添加了它:

myContext.Configuration.ProxyCreationEnabled = false;

我发帖,以便如果有人遇到此问题,请提供解决方案。