在集合上的`.fetch()`之后,Backbone下拉列表为空

时间:2013-12-05 18:16:39

标签: asp.net-mvc backbone.js

我们正在使用ASP.Net MVC 4并且有一个名为GetDistricts的JSONResult方法,它输出下面的结果。我遇到的问题是当我手动转到网址/Home/GetDistricts时,我得到下面的结果,但Backbone集合在调用fetch()时没有填充数据。我在调用它的代码中放置了一个断点,并验证this.districts是一个空数组。同样在Chrome检查器的“网络”选项卡中,对方法的AJAX调用成功(200)但响应为空。再次手动去那里会产生结果。我也确保设置JsonRequestBehavior.AllowGet

为什么我没有收到JSON结果?

骨干:

<script type="text/javascript">
    $(function() {
        //Model
        District = Backbone.Model.extend({
            idAttribute: 'DistrictKey',
            defaults: {
                DistrictKey: 0,
                DistrictName: null
            }
        });

        //Collection
        Districts = Backbone.Collection.extend({
            model: District,
            url: "/Home/GetDistricts"
        });

        //View
        DistrictDropdown = Backbone.View.extend({
            el: $("#district-dropdown"),
            initialize: function() {
                this.districts = new Districts;
                this.districts.fetch();
                this.render();
            },
            render: function() {
                this.$el.html(_.template($("#district-dropdown-template").html(), {districts: this.districts }));
                return this;
            },
            events: {
                "change #district-dropdown-control": "loadSchools",
            },
            loadSchools: function() {
                //Do work
            }
        });

        //Create the view
        var districtDropdown = new DistrictDropdown;
    });
</script>

模板:

<script type="text/template" id="district-dropdown-template">
    <select id="district-dropdown-control" name="districts">
        <% districts.each(function (district) { %>
            <option value="<%= district.get('DistrictKey') %>"><%= district.get('DistrictName') %></option>
        <% }); %>
    </select>
</script>

JSON从/ Home / GetDistricts返回:

[
    {
        "DistrictKey": 1,
        "DistrictName": "District A"
    },
    {
        "DistrictKey": 2,
        "DistrictName": "District B"
    },
    {
        "DistrictKey": 3,
        "DistrictName": "District C"
    }
]

1 个答案:

答案 0 :(得分:0)

我假设在fetch方法从服务器检索数据之前调用了render方法。

使用回调:

fetch({
    success: function() {
            // call render
    }
});