【问题标题】:Backbone Dropdown list empty after `.fetch()` on collection集合上的 .fetch() 后主干下拉列表为空
【发布时间】:2013-12-05 18:16:38
【问题描述】:

我们正在使用 ASP.Net MVC 4 并有一个名为 GetDistricts 的 JSONResult 方法,它输出以下结果。我遇到的问题是,当我手动转到 url /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>

从 /Home/GetDistricts 返回的 JSON:

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

【问题讨论】:

    标签: asp.net-mvc backbone.js


    【解决方案1】:

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

    使用回调:

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

    【讨论】:

    • 我该怎么做并且仍然保持this的正确上下文?
    • 你总是可以做旧的 var that = this;回调之前。然后 that.render();
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多