Home > Software engineering >  C# and Ajax - Posting 2 values from JS to C#
C# and Ajax - Posting 2 values from JS to C#

Time:01-13

I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.

JS:

function deleteConta(id) {
    var data = $("#monthSelector").val();
    
    var params = {
        id: id,
        dataAtual: data
    };
    
    $.ajax({
        type: "POST",
        url: '/Contas/ContaView?handler=Delete',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(params),
        headers:
        {
            "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
        },
        success: function (partialReturn) {
            $("#partial").html(partialReturn);
        }
    });
}

C#:

public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
    contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
    dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
    contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
    return Partial("_PartialContas", contas);
}

I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}

Checked a lot of forums, but Couldn't figure out how to make this thing work.

CodePudding user response:

By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class. Have you tried to remove it and sending value to the action?

—- UPDATE ——

Try this

function deleteConta(id) {
var data = $("#monthSelector").val();

$.ajax({
    type: "POST",
    url: '/Contas/ContaView?handler=Delete',
    data: { id: id, dataAtual: data },
    headers:
    {
        "RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
    },
    success: function (partialReturn) {
        $("#partial").html(partialReturn);
    }
});

}

  • Related