asp.net webapi backbone fetch()quirk?

时间:2012-05-17 09:38:08

标签: asp.net-mvc backbone.js httpresponse

我正在使用ASP.NET Web API实现一个服务点。它会返回一个列表,IEnumerable内嵌有HttpResponseMessage个dto。

但是,通过主干集合提取实现的客户端代码总是会出错。在错误方法里面,当我通过&观察参数我看到该集合出现在ResponseText属性下。

虽然我直接传递IEnumerable<dto>而没有用HttpResponseMessage包裹它,但它运行正常。

我的问题:正确的方法是什么?如何让我的骨干集合引用ResponseText属性中的内容?

我尝试使用单个模型获取,并覆盖fetch方法。

categories = new Categories({ url: 'http://localhost:6685/category' });

$.when(categories.fetch())
    .then(
        function() {
               app.init({ 'categories': categories, 'cart': cart });

               });

这一直给我一些模棱两可的错误。然后我换了

categories.fetch({
            success: function() {... },
            error: function(err) {

                console.log(err);
            }
        });

我可以看到里面的错误我的类别列表。属性名称为responsetext

var Categories = Backbone.Collection.extend({

    model: Category,

    initialize: function (options) {
        this.url = options.url;
    },

    parse:function (response) {
        return response.categories;
    },

服务器侧

HttpResponseMessage<IEnumerable<category>> httpresponse = null;

 var response= _catalogueservice.getcategories();

            if (response.success)
            {

                httpresponse =  new HttpResponseMessage<IEnumerable<category>>(response.categories, response.categories.Count()>0?HttpStatusCode.Found:HttpStatusCode.NotFound);
            }
            else
            {
                httpresponse = new HttpResponseMessage<IEnumerable<category>>( HttpStatusCode.NotFound);

            }

        return httpresponse;

我可以在fiddler下看到正在返回JSON。

1 个答案:

答案 0 :(得分:1)

始终保持您的服务干燥简单。当您发现大多数api用户因为您的方便而必须使用另一个数据包装器时,您就陷入了噩梦。无论如何,请将下面的内容放在一边

var todos = Backbone.Collection.extend({
url:"todoapi/gettodos",
parse:function(response){
   return response.Todos
}
});

考虑到您的回复如下所示

{Error:"NULL",Todos:[{Id:1,Todo:"Welcome"},{Id:2,Todo:"Eat"...}]}
相关问题