Felipe Deveza
Felipe Deveza

Reputation: 1969

Json post int type is always 0

[HttpPost("method")]
public string Method(int number)
{
    return number.ToString();
}

Why number is always 0?

Its possible to use json post with primitive types like this?

My post: { "number" : 3 }

Upvotes: 4

Views: 2598

Answers (2)

Mardoxx
Mardoxx

Reputation: 4482

public class NumberModel
{
    public int Number { get; set; }
}

[HttpPost("method")]
public IActionResult Method([FromBody] NumberModel model)
{
    return Ok(model.Number);
}

Will auto format it as Json. As Number is an integer, it will return as the string representation of the number. If you just return Ok(model) it will return an json object like { 'Number' : 3 }

Upvotes: 1

Set
Set

Reputation: 49779

If you post data like { "number" : 3 }, your action method should be

public class Data
{
   public int Number {get; set;}
}

[HttpPost("method")]
public string Method([FromBody] Data data)
{
    return data.Number.ToString();
}

Upvotes: 3

Related Questions