How to send data from AngularJS to an ASP.NET MVC backend?

4

What would be the best and simplest alternative?

I have the Web Api:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Generico.Dominio;
using Generico.Aplicacao;

namespace AspNetWebApi.Controllers
{
    [RoutePrefix("api/AspNetWebApi")]
    public class DefaultController : ApiController
    {

        //http://localhost:7630/api/AspNetWebApi/consulta/JogosPorID/5
        [HttpGet]
        [Route("consulta/JogosPorID/{id:int}")]
        public HttpResponseMessage JogosPorID(int id)
        {
            try
            {
                var tTabela = new  JogoDetalheAplicacao();
                var listar = tTabela.ListarTodos(id);
                return Request.CreateResponse(HttpStatusCode.OK, listar.ToArray());
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }



        //http://localhost:7630/api/AspNetWebApi/cadastrar/jogo/4512/20.01/20.10/5
        [HttpPost]
        [Route("cadastrar/jogo/{nJogo}/{valor}/{total}/{idusuario}")]
        public HttpResponseMessage Cadastro(int nJogo, decimal valor, decimal total, int idusuario)
        {
            try
            {
                var tTabela = new JogoDetalheAplicacao();
                tTabela.Inseri(nJogo, valor,total,idusuario);
                return Request.CreateResponse(HttpStatusCode.OK, "Cadastro realizado.");
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }


        //http://localhost:7630/api/AspNetWebApi/deletar/jogo/4512/5
        //precisa usar o postman com opção delete formato json
        [HttpDelete]
        [Route("deletar/jogo/{nJogo}/{idusuario}")]
        public HttpResponseMessage Deletar(int nJogo, int idusuario)
        {
            try
            {
                var tTabela = new JogoDetalheAplicacao();
                var resultado = tTabela.Excluir(nJogo, idusuario);
                return Request.CreateResponse(HttpStatusCode.OK, resultado);
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }


        //http://localhost:1608/api/ApiGuiaCidade/datahora/consulta
        [HttpGet]
        [Route("datahora/consulta")]
        public HttpResponseMessage GetDataHoraServidor()
        {
            try
            {
                var dataHora = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
                return Request.CreateResponse(HttpStatusCode.OK, dataHora);
            }
            catch (Exception ex)
            {

                return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
            }
        }



    }
}

I have the Script:

(function () {
    'use strict';

    var numeros = angular
    .module("myModule", [])
    .controller("myController", function ($scope, $http, $log) {

        var sv = this;

        var sucessoCalBack = function (response) {
            $scope.detalhes = response.data;
        };

        var erroCalBack = function (response) {
            $scope.error = response.data;
        };


        //assim funciona, passando o parametro direto 
        $http({
            method: 'GET',
            params: { idusuario: 5 },
            url: 'http://localhost:7630/api/AspNetWebApi/consulta/JogosPorID/5'})
             .then(sucessoCalBack,erroCalBack);
        });


        sv.getAll = function (idusuario, onSuccess, onFail) {
            var config = {
                method: 'GET',
                url: 'http://localhost:7630/api/AspNetWebApi/consulta/JogosPorID/',
                params: { idusuario:idusuario }
            };
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };


            //Inser Detalhe
        sv.post = function (nJogo, valor, total, idusuario, onSuccess, onFail) {
                var config = {
                    method: 'POST',
                    url: 'http://localhost:7630/api/AspNetWebApi/cadastrar/jogo/',
                    params: { nJogo: nJogo, valor: valor, total: total, idusuario: idusuario }
                }; 
                $http(config)
                    .then(function (response) {
                        onSuccess(response.data);
                    }, function (response) {
                        onFail(response.statusText);
                    });
            };


       //Delete detalhe
        sv.delete = function (idusuario,numerojogo , onSuccess, onFail) {
            var config = {
                method: 'DELETE',
                url: 'http://localhost:7630/api/AspNetWebApi/deletar/jogo/',
                params: { idusuario: idusuario, numerojogo: numerojogo }
            }
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };



})();

Final result:

Questions:

1-IneedtogetGetpassingaparameterthatwouldbetheUserID

2-IneedtodothepostanddeletealsosendingtheUserIDisgamenumber

I'mmakingtheprojectcomplete,there'sonlyonetable(withscriptalreadywithdata),ifanyonecanhelpmelearnthis,I'musingVS2015,thankyou.

link

    
asked by anonymous 04.01.2016 / 02:12

1 answer

5

Customer

The recommended way to do this is to create a service in AngularJS that will be in charge of communicating with the server, this service will then expose functions that will be used as controllers communication interfaces.

One concept that you need to keep in mind is this:

╔════════════════════════════════════════╦═══════════════════════════════════╗
║ Controllers                            ║ Services                          ║
╠════════════════════════════════════════╬═══════════════════════════════════╣
║ Lógicas da apresentação (view)         ║ Lógicas de negócio                ║
║----------------------------------------║-----------------------------------║
║ Coisas diretamente relacionadas à view ║ Coisas que independem da view     ║
║----------------------------------------║-----------------------------------║
║ Coisas específicas                     ║ Coisas reutilizáveis              ║
║----------------------------------------║-----------------------------------║
║ Responsável por buscar os dados no     ║ Responsável por fazer requisições ║
║ servidor, por exibir os dadoss, por    ║ ao servidor, por lógicas de       ║
║ gerenciar interações do usuário, por   ║ validação, armazenamento de dados ║ 
║ estilos e exibição de partes da UI     ║ dentro do app e reutilização de   ║
║                                        ║ lógicas de negócio                ║
╚════════════════════════════════════════╩═══════════════════════════════════╝

Source: This table is an adaptation to Portuguese of one that can be found in the book AngularJS Up and Running >.

Here is an example of a service that I put together to communicate with a RESTFul API that manages products. It uses an service from AngularJS itself called $http to perform the HTTP requests:

(function () {
    'use strict';

    angular
        .module('app')
        .service('products', products);

    products.$inject = ['$http', 'user', 'API_URL'];

    function products($http, user, API_URL) {
        var sv = this;
        var endpoint = API_URL + '/products';

        sv.getAll = function (onSuccess, onFail) {
            var config = {
                method: 'GET',
                url: endpoint
            };
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };

        sv.getById = function (id, onSuccess, onFail) {
            var config = {
                method: 'GET',
                url: endpoint,
                params: { id: id }
            };
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };

        sv.post = function (newProduct, onSuccess, onFail) {
            var config = {
                method: 'POST',
                url: endpoint,
                data: newProduct
            };
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };

        sv.put = function (updatedProduct, onSuccess, onFail) {
            var config = {
                method: 'PUT',
                url: endpoint,
                params: { id: updatedProduct.id },
                data: updatedProduct
            };
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };

        sv.delete = function (id, onSuccess, onFail) {
            var config = {
                method: 'DELETE',
                url: endpoint,
                params: { id: id }
            }
            $http(config)
                .then(function (response) {
                    onSuccess(response.data);
                }, function (response) {
                    onFail(response.statusText);
                });
        };
    }
})();

And how would you use this service in controller ? Here is an example of the service being used:

(function () {
    'use strict';

    angular
        .module('app')
        .controller('MainController', MainController);

    MainController.$inject = ['$scope', 'products', 'user'];

    function MainController($scope, products, user) {
        var vm = this;

        vm.products = [];

        products.getAll(function (data) {
            vm.products = data;
        }, function (errorMessage) {
            alert(errorMessage);
        });

        vm.deleteProduct = function (id) {
            if (!confirm("Would you like to delete this product?")) {
                return;
            }   

            products.delete(id, function (response) {
                var productIndex = vm.products.findIndex(function (value, index, traversedObject) {
                    return value.Id === id;
                });

                if (productIndex > -1) {
                    vm.products.splice(productIndex, 1);
                }

                alert('Product successfully deleted');
            }, function (errorMessage) {
                alert(errorMessage);
            });
        };
    }
})();

Server

The ASP.NET MVC service can be created using a action method that returns an #, here is a simple example:

public async Task<ActionResult> GetSomeJsonData()
{
    var model = new { Name = "João", LastName = "Silva" };

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

But I recommend you take a look at the ASP.NET Web API. Unlike ASP.NET MVC, the ASP.NET Web API is a framework specifically designed for creating RESTFul APIs.

It has many features that help you to develop an API faster, such as integration by default with Json.NET to "serialize" objects in JSON, among other things.

    
04.01.2016 / 02:34