【发布时间】: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"
}
]
【问题讨论】: