Reputation: 3999
I need to post 4 parameters from AJAX to MVC api method. Api method is called but all variables have default values. Year and month is zero and app and levels has null value.
Any idea what is an issue in my code?
$.ajax({
url: "/api/home/GetLogList",
method: 'POST',
dataType: 'json',
data: { year: 2017, month: 5, app: "hello", levels: ["aa", "bb"] },
contentType: 'application/json; charset=utf-8',
success: function (logs) {
alert("successs");
},
error: function (jqXHR, textStatus) {
alert("fail");
}
})
API
[HttpPost]
[Route("api/home/GetLogList")]
public async Task<IEnumerable<Log>> GetLogList(int year, int month, string app, IEnumerable<string> levels)
{
using (var client = new HttpClient())
{
var refreshedLogs = await GetLogList(client, year, month, app, null);
return refreshedLogs;
}
}
Upvotes: 0
Views: 550
Reputation: 720
I think your only solution is to create a viewModel for the method parameters?
public class LogListVM {
public int year { get; set; }
public int month { get; set; }
public string app { get; set; }
public IEnumerable<string> levels { get; set; }
}
[HttpPost]
[Route("api/home/GetLogList")]
public async Task<IEnumerable<Log>> GetLogList(LogListVM params)
{
using (var client = new HttpClient())
{
var refreshedLogs = await GetLogList(client, params.year, params.month, params.app, null);
return refreshedLogs;
}
}
JS does not change.
Upvotes: 2
Reputation: 1021
contentType: 'application/json; charset=utf-8'
data type to send in json format - in your case you need to convert into json
dataType: 'json'
Return type of data from server to json
$.ajax({
url: "/api/home/GetLogList",
contentType: 'application/json; charset=utf-8', // data type to be send to server in json format
method: 'POST',
dataType: 'json', // return type of data from server - should be json
data:JSON.stringify( { year: 2017, month: 5, app: "hello", levels: ["aa", "bb"] }),
success: function (logs) {
alert("successs");
},
error: function (jqXHR, textStatus) {
alert("fail");
}
});
Upvotes: 0