[英]How to post four parameters from ajax to MVC API controller
I need to post 4 parameters from AJAX to MVC api method. 我需要将4个参数从AJAX发布到MVC api方法。 Api method is called but all variables have default values. 调用了Api方法,但是所有变量都有默认值。 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 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? 我认为您唯一的解决方案是为方法参数创建viewModel?
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. JS不变。
contentType: 'application/json; contentType:'application / json; charset=utf-8' charset = utf-8'
data type to send in json format - in your case you need to convert into json 数据类型以json格式发送-在您的情况下,您需要转换为json
dataType: 'json' dataType:'json'
Return type of data from server to json 将数据类型从服务器返回到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");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.