1

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.

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

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.