Reputation: 1901
I have an ajax call:
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: {"keytype": "1"},
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
and my controller method:
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]string keytype)
{
try
{
return Ok();
}
catch (Exception ex)
{
}
}
So, inititally I wanted to send an enum type, but that didnt work, so I wanted to send an int with value 1
and I kept getting only 0, then I added [FromBody]
and it was the same, at last I switched to string just in case, and now Im getting a null value.
Where I went wrong in all this variations?
Upvotes: 2
Views: 1465
Reputation: 3746
You must stringify your data.
Try the following:
$.ajax({
url: "/profile/GuestList",
data: JSON.stringify({"keytype": "1"}),
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
Upvotes: 0
Reputation: 608
You have to update your data in your Ajax call to a string as you are using string as input parameter in your POST method.
...
$("#testBtn").click(function (e) {
e.preventDefault();
$.ajax({
url: "/profile/GuestList",
data: "1",
method: "POST",
contentType: "application/json",
success: function (data) {
...
}
});
});
...
Upvotes: 0
Reputation: 43890
Create class
public class KeyTypeViewModel
{
public string Keytype { get; set; }
}
Fix action by removing [FromBody]
[HttpPost]
public async Task<IActionResult> GuestList(KeyTypeViewModel viewModel)
And fix ajax by removing contentType: "application/json" :
$.ajax({
url: "/profile/GuestList",
data: {keytype: "1"},
method: "POST",
success: function (data) {
...
}
Upvotes: 3
Reputation: 12305
You need to create a Dto that has property keytype.
public class SomeDto
{
public string Keytype { get; set; }
}
[HttpPost]
public async Task<IActionResult> GuestList([FromBody]SomeDto dto)
Upvotes: 2