I have two json array. I’m trying to send these json array to my controller. When i want to send one of them, everything is fine but i couldnt’t send second one. How can i fix it ?
Post function from view
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) { }
});
}
Controller
[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; }
}
3
Answers
The issue is with the following line:
This is an object in javascript. The equivalent in c# should be:
And then in your controller:
For more information, check Why does ASP.NET Web API allow only one parameter for POST method?
Solution
Happy coding, cheers!
I tried your code and it works fine for me except for some things.
First your second parameter has a different ViewModel on what you have posted on your code:
But on your parameter, you are using a different ViewModel:
As you can see here,
IlgiAlanVM
is different onList<IlgiAlanlarVM>
Second, I just I used the same code but without the
[FromBody]
. So that would be:Lastly, I just make sure it’s an array of objects to make sure it will bind nicely on your list of models: