Getting value from array mvc

2

I'm passing an angular array by JSON this way:

 $scope.gravaItem = function () {
        $.ajax({
            type: 'GET',
            url: '/TaxaPreco/SalvarItens',
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            data: { DeJson: JSON.stringify($scope.items) },
            success: function (result) {
                console.log('Data received: ');
                console.log(result);
            }

        })
    };

And no controller this way:

 public async Task<ActionResult> SalvarItens(string DeJson)
    {
        var arr = DeJson.Split(',');
        var item = new TarifasPrecosItens()
        {
            De = arr[0],
            Ate = "01:01",
            Fracao = 0,
            RepeteACada = 0,
            TipoValor = 1,
            Valor =5,
            TararifaPrecosId = 25,
        };

        _context.TarifasPrecosItens.Add(item);
        _context.SaveChanges();


        return new JsonResult(DeJson);
    }

In it it gets the following value:

  

[{"de": "00:01"

How can I resolve the value correctly? I need to get all the values, in this case I should just get:

  

00:01

    
asked by anonymous 07.06.2018 / 16:48

1 answer

0

I would not use stringify to pass the list to the controller. If items is an array of strings simply do:

$scope.gravaItem = function () {
    $.ajax({
        type: 'GET',
        url: '/TaxaPreco/SalvarItens',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        data: { DeJson: $scope.items },
        success: function (result) {
            console.log('Data received: ');
            console.log(result);
        }

    })
};

and no controller:

public async Task<ActionResult> SalvarItens(List<string> DeJson)
{
    var item = new TarifasPrecosItens()
    {
        De = DeJson.First(),
        Ate = "01:01",
        Fracao = 0,
        RepeteACada = 0,
        TipoValor = 1,
        Valor =5,
        TararifaPrecosId = 25,
    };

    _context.TarifasPrecosItens.Add(item);
    _context.SaveChanges();


    return new JsonResult(DeJson);
}

There is an excellent article that shows you how to use $ scope with Asp.NET MVC: Call MVC Controller from AngularJS using AJAX and JSON in ASP.Net MVC

Att

    
04.07.2018 / 20:04