Taking value from mvc array

Asked

Viewed 74 times

2

I’m passing an angular array through 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 in the controller in 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 receives the following value:

[{"of":"00:01"

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

00:01

1 answer

0

I wouldn’t use stringify to pass the list to the controller. If items is a string array just 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 in the 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 showing how to use $Scope with Asp.NET MVC: Call MVC Controller from Angularjs using AJAX and JSON in ASP.Net MVC

Att

Browser other questions tagged

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