我们正在使用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"
}
]
答案 0 :(得分:0)
我假设在fetch方法从服务器检索数据之前调用了render方法。
使用回调:
fetch({
success: function() {
// call render
}
});