的AngularJS $资源工作的例子在搜索网页API项目 [英] Working example of AngularJS $resource searching items in Web Api

查看:142
本文介绍了的AngularJS $资源工作的例子在搜索网页API项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何使用AngularJS的$资源来调用Web阿比后端。我想传递一个对象层次作为标准,并取回一个的IEnumerable<程序> 。下面是标准的例子:

I'm learning how to use AngularJS's $resource to call a Web Api backend. I want to pass an object hierarchy in as criteria and get back an IEnumerable<Program>. Here's an example of the criteria:

$scope.criteria = {
    Categories:[
        {
            Name: "Cat1",
            Options: [
                {Text: "Opt1", Value: true},
                {Text: "Opt2", Value: false}
            ]
        },
        {
            Name: "Cat2",
            Options: [
                {Text: "Opt3", Value: true},
                {Text: "Opt4", Value: false}
            ]
        }
    ]
}

我在C#中的服务器上定义相同的对象。

I have the same objects defined on the server in C#.

public class CriteriaModel
{
   public IEnumerable<CriteriaCategory> Categories { get; set; }
}

public class CriteriaCategory
{
    public string Name { get; set; }
    public IEnumerable<CriteriaOption> Options { get; set; }
}

public class CriteriaOption
{
    public string Text { get; set; }
    public bool Value { get; set; }
}

下面是如何,我在配置资源$

Here's how I am configuring $resource:

angular.module('my.services')
    .factory('api', [
        '$resource',
        function ($resource) {
            return {
                Profile: $resource('/api/profile/:id', { id: '@id' }),
                Settings: $resource('/api/settings/:id', { id: '@id' }),
                Program: $resource('/api/program/:id', { id: '@id' })
            };
        }
    ]);

和我叫它是这样的:

api.Program.query({ criteria: $scope.criteria }, function (response) {
    $scope.programs = response;
});

不管是什么我尝试我要么得到作为标准参数或动作根本不执行。我不知道问题出在棱角分明,网页API,或两者兼而有之。这里是动作:

No matter what I try I either get null as the criteria parameter or the action doesn't execute at all. I don't know if the problem is in angular, web api, or both. Here is the action:

public class ProgramController : ApiController
{
    public IEnumerable<Program> GetByCriteria([FromUri]CriteriaModel criteria)
    {
        // Either criteria is null or this action doesn't even get
        // executed depending on what I try.
    }
}

有人可以帮助我获得了一个工作的例子去搜索和返回使用AngularJS $资源和网页API项目?

Can someone help me get a working example going for searching and returning items using AngularJS $resource and Web Api?

推荐答案

您会需要自定义模型粘合剂。从<一个href=\"http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/\">what我明白 FromUri 不会处理其复杂的嵌套类型或JSON $资源将投入查询字符串

You're going to need a custom model binder. From what I understand FromUri will not handle complex nested types or json which $resource will put in the query string.

Github上采样

模型绑定:

public class CriteriaModelBinder : IModelBinder
{
    public bool BindModel(
        HttpActionContext actionContext,
        ModelBindingContext bindingContext
    )
    {
        if (bindingContext.ModelType != typeof (CriteriaModel))
        {
            return false;
        }

        var value = bindingContext.ValueProvider.GetValue("Categories");

        if (value == null)
        {
            return false;
        }

        var categoryJson = value.RawValue as IEnumerable<string>;

        if (categoryJson == null)
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName, "Categories cannot be null.");
            return false;
        }

        var categories = categoryJson
            .Select(JsonConvert.DeserializeObject<CriteriaCategory>)
            .ToList();

        bindingContext.Model = new CriteriaModel {Categories = categories};
        return true;
    }
}

控制器:

[RoutePrefix("api/program")]
public class ProgramController : ApiController
{
    [Route("getbycriteria")]
    [HttpGet]
    public HttpResponseMessage GetByCriteria(
        [ModelBinder(typeof(CriteriaModelBinder))]CriteriaModel criteria
    )
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

角控制器:

angular.module('myApp').
    controller('HomeController', function($scope, $resource) {
        var Program = $resource('/api/program/:id', {}, {
            getByCriteria: {
                url: '/api/program/getbycriteria',
                method: 'GET',
                isArray: true
            }
        });

        var program = new Program();
        var criteria = {
            Categories: [
                {
                    Name: "Cat1",
                    Options: [
                        { Text: "Opt1", Value: true },
                        { Text: "Opt2", Value: false }
                    ]
                },
                {
                    Name: "Cat2",
                    Options: [
                        { Text: "Opt3", Value: true },
                        { Text: "Opt4", Value: false }
                    ]
                }
            ]
        };

        $scope.submit = function () {
            console.log(program);
            program.$getByCriteria(criteria);
        };
    });

编辑:

下面是 POST

控制器:

[RoutePrefix("api/program")]
public class ProgramController : ApiController
{
    [Route("getbycriteria")]
    [HttpPost]
    public HttpResponseMessage GetByCriteria(CriteriaModel criteria)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

角:

angular.module('myApp').
    controller('HomeController', function($scope, $resource) {
        var Program = $resource('/api/program/:id', {}, {
            getByCriteria: {
                url: '/api/program/getbycriteria',
                method: 'POST',
                isArray: true
            }
        });

        var program = new Program();
        program.Categories = [
                {
                    Name: "Cat1",
                    Options: [
                        { Text: "Opt1", Value: true },
                        { Text: "Opt2", Value: false }
                    ]
                },
                {
                    Name: "Cat2",
                    Options: [
                        { Text: "Opt3", Value: true },
                        { Text: "Opt4", Value: false }
                    ]
                }
            ];

        $scope.submit = function () {
            console.log(program);
            program.$getByCriteria();
        };
    });

这篇关于的AngularJS $资源工作的例子在搜索网页API项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆