Doubt in passing parameters via AJAX to ASP NET CORE Action

Asked

Viewed 290 times

1

Friends, I’m having trouble passing a value to the action of a specific controller that takes as parameter an id of type int.

AJAX

var dataForm = $("#statisticId").val();


        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: "Statistic",
            dataType: "json",
            data: dataForm,
            success: function (_response) {
                console.log(_response);
            }
        });

Action Statistic

[HttpPost]
public IActionResult Statistic([FromBody]int dataForm)
{
    var statistics = statisticPatientBLL.GetStatisticById(dataForm);
    return Json(statistics);
}

I have checked if you are actually passing any value, and yes, it displays correctly when I collect the value of an HTML element. I couldn’t find an answer to that. Could anyone help me? Would it be a problem in the matter of routes? What’s wrong with this code?

2 answers

1


You already managed to solve your problem, but I leave here some corrections in the settings of your AJAX, maybe it helps you:

var id = $("#statisticId").val();
    console.log(id);

    $.ajax({
        contentType: "text/plain",
        type: "POST",
        url: "/Answer/Statistic/",
        data: id,
        dataType: "json",
        success: function (_response) {
            console.log(_response);
        }
    });
};

In the above example instead of concatenating in URL I used the parameter data to set the value to be sent in post. See more about the AJAX settings parameters.

A problem I also noticed in the configuration of your AJAX is that the contentType is as application/json. In your case as you are sending only one 'id' you should use text/plain, as is in my example.

  • George, I made the changes by following their structure, but I couldn’t get the id value. What might be in this case?

  • @Felipeprestes, I realized now that I left this date part: id, no comma, I just edited and put it, must be this.

0

I was able to identify the error. It was missing to add the full path to the URL in AJAX.

The corrected section was thus:

var id = $("#statisticId").val();
    console.log(id);

    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: "/Answer/Statistic/ " + id,
        dataType: "json",
        success: function (_response) {
            console.log(_response);
        }
    });
};

Browser other questions tagged

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