简体   繁体   中英

Json integer turns string when posting Data .Net Core + React

I am trying to add Car objects to my Database, it's working fine with just strings, but when i try to add an integer value, the value gets quoted in the Json and so turned to string. Here's my.Net Core Model:

public class Car : Service
    {
        public string Description { get; set; }
        public int Price { get; set; }
        public string Options { get; set; }
    }

Here's my create handler

 public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var car = new Car
                {
                    id = request.id,
                    Name = request.Name,
                    Description = request.Description,
                    Price = request.Price,
                    Options = request.Options
                };

                _context.Cars.Add(car);
                var success= await _context.SaveChangesAsync() > 0;

                if(success) return Unit.Value;

                throw new System.Exception("Problem saving changes");
            }

Again the create handler works fine with strings but when i try to send an integer value, here's the Json that's sent

{id: "f8aa6881-8a90-4510-9505-5471c1f9a656", name: "Mercedes AMG", description: "a", price: "800",…}
description: "a"
id: "f8aa6881-8a90-4510-9505-5471c1f9a656"
name: "Mercedes AMG"
options: "a"
price: "800" //This is the value creating the problem
price:{}; The JSON value could not be converted to System.Int32

Please how can i make sure the value gets passed as an integer? i appreciate the help.

Found myself with this issue today!

You could use valueAsNumber to get the value as a double

double : Returns the value of the element, interpreted as one of the following, in order:

  • A time value
  • A number
  • NaN if conversion is impossible

source - MSN Web Docs

If you're using a basic "onChange" type function to handle the input, you could alter it to something like (where if it is not a number, it will assign it as a string like normal):

    onChange = e => this.setState({ [e.target.name]: e.target.valueAsNumber || e.target.value })

or if you need a bit more finite control over your conversions, you could do something similar to what @ bennygenel suggested in his answer :

this.setState({
  [e.target.name]: e.target.type === 'number' ? parseInt(e.target.value) : e.target.value
});

// or

this.setState({
  [e.target.name]: e.target.name === 'price' ? parseFloat(e.target.value) : e.target.value
});

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM