如何解决如何将多个json数组从ajax传递到控制器?
我有两个json数组。我正在尝试将这些json数组发送到我的控制器。当我想发送其中一个时,一切都很好,但我无法发送第二个。我该如何解决?
从视图中发布功能
function HobiIlgiAlanKaydetGuncelle() {
var hobiler = $('#Hobiler').val(); // Json array of object
var ilgiAlanlar = $('#IlgiAlan').val();
$.ajax({
url: "/Kullanici/HobiVeIlgiAlanlariniKaydetGuncelle",type: "POST",contentType: 'application/json; charset=UTF-8',dataType: 'json',data: {hobiler : hobiler,ilgiAlanlar : ilgiAlanlar},success: function (response) { }
});
}
控制器
[HttpPost]
public async Task<JsonResult> HobiVeIlgiAlanlariniKaydetGuncelle([FromBody] List<HobilerVM> hobiler,List<IlgiAlanlarVM> ilgiAlanlar)
{
//When I put second parameter,both of them comes with null
}
HobilerVM
public class HobilerVM
{
public int id { get; set; }
public string value { get; set; }
}
IlgiAlanVM
public class IlgiAlanVM
{
public int id { get; set; }
public string value { get; set; }
}
解决方法
问题出在以下几行:
data: {hobiler : hobiler,ilgiAlanlar : ilgiAlanlar}
这是javascript中的对象。 C#中的等效项应为:
public class MyData {
public List<HobilerVM> hobiler;
public List<IlgiAlanlarVM> ilgiAlanlar;
}
然后在您的控制器中:
[HttpPost]
public async Task<JsonResult> HobiVeIlgiAlanlariniKaydetGuncelle([FromBody] MyData data)
{
//When i put second parameter,both of them comes with null
}
有关更多信息,请选中Why does ASP.NET Web API allow only one parameter for POST method?
,Web API不允许您在 Web API控制器方法的方法签名-您只能发布一个 Web API操作方法的单个值。该值甚至可以 是一个复杂的对象。虽然可以传递多个值 通过将一个参数映射到实际值来执行POST或PUT操作 内容和其余内容通过查询字符串。参考: How to pass multiple parameters to Web API controller methods和How WebAPI does Parameter Binding
解决方案
export type ExpandedFiltered = {
[key: string]: string | number[] | Moment[] | FilterData[]
}
编码愉快,加油!
,我尝试了您的代码,除了某些方面,它对我来说很好用。
第一个参数与您在代码上发布的内容不同,它具有另一个ViewModel:
public class IlgiAlanVM
{
public int id { get; set; }
public string value { get; set; }
}
但是在您的参数上,您使用的是其他ViewModel:
([FromBody] List<HobilerVM> hobiler,List<IlgiAlanlarVM> ilgiAlanlar)
正如您在此处看到的,IlgiAlanVM
在List<IlgiAlanlarVM>
上是
第二,我只是使用了相同的代码,但没有使用[FromBody]
。这样就可以了:
//I already edited your List of Model here on the second parameter from IlgiAlanVM to IlgiAlanlarVM
[HttpPost]
public async Task<JsonResult> HobiVeIlgiAlanlariniKaydetGuncelle
(List<HobilerVM> hobiler,List<IlgiAlanlarVM> ilgiAlanlar)
最后,我只是确保它是一个对象数组,以确保它可以很好地绑定在您的模型列表中:
var hobiler = [{
id: 1,value: 'My Value'
}];
var ilgiAlanlar = [{
id: 1,value: 'MyValue'
}];
$.ajax({
url: '@Url.Action("HobiVeIlgiAlanlariniKaydetGuncelle","Kullanici")',type: "POST",contentType: 'application/json; charset=UTF-8',dataType: 'json',data: JSON.stringify({ hobiler : hobiler,ilgiAlanlar : ilgiAlanlar }),success: function (response) { }
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。