After analyzing better, I believe the only problem was the order of the parameters in your url, for example, you were doing so:
$.ajax({
url: '@Url.Action("ClienteConfiguracaoPlano","ObtemContaPagamento")',
type: "POST",
data: { id: 21},
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
while the correct url would be:
$.ajax({
url: '@Url.Action("ObtemContaPagamento", "ClienteConfiguracaoPlano")',
type: "POST",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ id: 21}),
dataType: 'json',
cache: false,
async: true,
success: function (data) {
alert(data);
}
});
First you must pass the name of the Action, and then the name of the Controller.
Notice also that I used:
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ id: 21}),
dataType: 'json',
For data to be sent and received by JSON.
Well, as I said in the posts, I suggest changing your Action method to [HttpGet]
instead of [HttpPost]
, since your request only gets data and does not change anything.
This way it is safer because the [HttpGet]
method only accepts the request of data and not the modification of them in the server.
There are cases that it will be necessary to use [HttpPost]
, when for example you have to pass as an Action parameter, some more complex data, such as a class that has some property with some more complex type, that is, IEnumerable or some other class within it. In this case you would have to use [HttpPost]
because [HttpGet]
only accepts simple parameters, eg: { parametro: valor }
.
In this case, your request would look like this:
$.get('@Url.Action("ObtemContaPagamento", "ClienteConfiguracaoPlano")', { id: 21 }, function(data) {
alert(data);
});
Another suggestion I make is to use a friendlier form of url, such as:
$.get('/ClienteConfiguracaoPlano/ObtemContaPagamento', { id: 21 }, function(data) {
alert(data);
});
Or even better, so as not to have problems with more routes, I usually do the following.
In my HTML I put an input to type hidden with the url inside and I get this url by javascript, so I think it gets more typed and safe, like this:
No HTML:
<input type="hidden" id="url-obtem-conta-pagamento" value="@Url.Action("ObtemContaPagamento", "ClienteConfiguracaoPlano")" />
No javascript:
var urlObtemContaPagamento = $('#url-obtem-conta-pagamento').val();
$.get(urlObtemContaPagamento, { id: 21 }, function(data) {
alert(data);
});
In this way you ensure that you are taking the correct route and get more typed.
To understand better about routes in ASP.NET MVC, I found article that explains rightly how it works in a very clear way.
I hope I have helped.
Hugs!