gpt4 book ai didi

c# - 如何在 .NET MVC 中返回 Backbone 集合

转载 作者:行者123 更新时间:2023-11-28 02:05:23 24 4
gpt4 key购买 nike

我正在使用 .NET MVC 获取主干集合,但无法正确填充该集合。我需要的数据已返回,但在集合中插入不正确。

以下是与获取集合相关的所有详细信息。

我的模型

_.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
});

Controller 方法

        [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

我显然做错了什么,但我不知道如何格式化要返回的数据。您可以看到它实际上以称为“模型”的对象数组的形式添加了一个子级别。

最佳答案

尝试在 Controller 操作中返回实际模型列表:

    [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 属性,请覆盖您的 collection's parse method从响应中返回 models 属性:

My.Collection.UserAssistance = Backbone.Collection.extend({

url: function () {
return '/user-assistance'
},

model: My.Model.UserAssistance,

parse: function (resp, options) {
return resp.models;
}
});

关于c# - 如何在 .NET MVC 中返回 Backbone 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com