如何在.NETMVC中返回主干集合
本文关键字:集合 返回 NETMVC | 更新日期: 2023-09-27 18:25:03
我正在使用.NETMVC获取主干集合,并且在正确填充集合时遇到问题。我需要的数据已返回,但在集合中插入错误。
以下是与获取集合相关的所有详细信息。
我的型号
_.namespace('My.Model');
My.Model.UserAssistance = Backbone.Model.extend({
defaults: {
Id : '',
Title: '',
Content: '',
Width: 175,
Popover: true,
ArrowPosition: "top-left",
ArrowDimensions: {
width: 0,
height: 0
}
}
});
我的收藏
_.namespace('My.Collection');
My.Collection.UserAssistance = Backbone.Collection.extend({
url: function () {
return '/user-assistance'
},
model: My.Model.UserAssistance
});
获取集合
this.collection = new My.Collection.UserAssistance();
var $elements = $('[data-help-id]'),
values = $elements.map(function () {
return $(this).data('help-id');
}).get();
this.collection.fetch({
data: {
HelpIds : values
},
// required for correct serialization of the array
traditional: true
});
控制器方法
[Authorize]
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Default(List<string> HelpIds)
{
List<UserAssistanceViewModel> models = new List<UserAssistanceViewModel>();
foreach (string helpId in HelpIds)
{
UserAssistanceViewModel model = new UserAssistanceViewModel();
model.Content = (Resources.UserAssistance.Content.GetResourceById(helpId));
model.Title = (Resources.UserAssistance.Titles.GetResourceById(helpId));
model.Id = helpId;
models.Add(model);
}
return Json(new
{
models : models
}, JsonRequestBehavior.AllowGet);
}
当返回集合时,集合更新如下:
userAssistance.collection.toJSON()
[
Object
ArrowDimensions: Object
ArrowPosition: "top-left"
Content: ""
Id: ""
Popover: true
Title: ""
Width: 175
models: Array[6]
0: Object
1: Object
2: Object
3: Object
4: Object
5: Object
length: 6
__proto__: Array[0]
__proto__: Object
我显然做错了什么,但我不知道如何格式化要返回的数据。您可以看到,它实际上是在添加一个子级别,其形式是一个名为"模型"的对象数组。
尝试在控制器操作中返回实际型号列表:
[Authorize]
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult Default(List<string> HelpIds)
{
List<UserAssistanceViewModel> models = new List<UserAssistanceViewModel>();
foreach (string helpId in HelpIds)
{
UserAssistanceViewModel model = new UserAssistanceViewModel();
model.Content = (Resources.UserAssistance.Content.GetResourceById(helpId));
model.Title = (Resources.UserAssistance.Titles.GetResourceById(helpId));
model.Id = helpId;
models.Add(model);
}
return Json(models, JsonRequestBehavior.AllowGet);
}
如果您绝对必须保留models
属性,请重写集合的解析方法以从响应返回models
属性:
My.Collection.UserAssistance = Backbone.Collection.extend({
url: function () {
return '/user-assistance'
},
model: My.Model.UserAssistance,
parse: function (resp, options) {
return resp.models;
}
});