简体   繁体   中英

How to post four parameters from ajax to MVC API controller

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;
    }
}

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.

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");
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM