2

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?

0

4 Answers 4

3

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) {
           ...
        }
Sign up to request clarification or add additional context in comments.

Comments

2

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)

2 Comments

but theres no really need to wrap one property into whole class?
if you see in Post ajax call you are sending an object {"keytype": "1"}.
0

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) {
           ...
        }
    });
});
...

Comments

0

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) {
           ...
        }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.