How to send Angularjs data to an ASP.NET MVC backend?

Asked

Viewed 1,197 times

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: inserir a descrição da imagem aqui

Doubts:

1 - I need to do Get by passing a parameter that would be the User ID

2 - I need to post and delete also sending the User ID is game number

I am providing the complete project, has only 1 table (with script already with data), in case someone can help me learn this, I am using VS 2015, I thank you.

https://drive.google.com/folderview?id=0B-svO0-4L_-NZF9pWFVwV3p4Wms&usp=sharing

1 answer

5

Client

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

One concept that needs to be borne in mind is the following:

╔════════════════════════════════════════╦═══════════════════════════════════╗
║ 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’s an example of a service I set up to communicate with a Restful API that manages products. It uses a service of Angularjs himself called $http to perform 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 make use of that service in the controller? Well, here’s an example from service above 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 through a action method that returns a Jsonresult, Below 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 developed specifically for creating Restful Apis.

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

  • Have questions, so I can’t send the data directly to the controller? , I just need to make a data post : number is value, how could I make this serve?

  • @itasouza updated my answer by adding some information on how to controllers and services should be used and how to use the service of the example in a controller. I hope this makes it clear to you. :)

  • I will create a service and prepare it to receive the data, so get ready if you have questions I return the question, I really appreciate your help.

  • I set up the service, I did the tests is until I can return the data, more I can not follow, see I changed my code, I also posted the project that only has 1 table, would you help me to do this? thanks

  • @itasouza To make a GET you pass the data by parameter using the property params in the configuration object of service $http, take a look at my example of service and look for the method sv.getById. About the POST, you pass the data using the property data in the configuration object of service $http, take a look at my example and look for the method sv.post.

  • I made the adjustments, posted the code and added a copy in Google Drive, see if it is correct, see if anything is missing, I appreciate the help!

  • I’m uploading a copy of the project, the link is at the end of the question, in google Drive, only it will take about 10 minutes, it’s going up is slow today.

  • @itasouza From what I saw here is right, I would only make some changes to the code as perfumery, but the way it is seems to be working properly.

  • @itasouza No need, I ended up seeing after that you also put in question the code. xD

  • @itasouza If you are interested, this article here is a style guide for you to format your code in Angularjs in the best way possible, so that it is easier to maintain in the future. https://github.com/johnpapa/angular-styleguide

  • I still have doubts, it is still difficult to understand, so if possible do there adjustments, I changed the get see if it will work when I send the Angular parameter, in this case I will need to have this project separate just to keep receiving the angular data? I’ll see the article

  • Do you have any way to test Sv.getAll?

  • Well, you can test it using a button in the application, then you use the Directive ng-click and passes on to it the call of a function of controller. Type, ng-click="ctrl.salvarProduto()".

  • i needed an example more within the reality of the code if possible: <button class="btn btn-Primary btn-block " ng-click="myController.getAll(5)">List Data</button>

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.