[英]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.我正在尝试将 Car 对象添加到我的数据库中,仅使用字符串就可以正常工作,但是当我尝试添加 integer 值时,该值在 Json 中被引用,因此转向字符串。 Here's my.Net Core Model:
这是 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再次,创建处理程序可以很好地处理字符串,但是当我尝试发送 integer 值时,这是发送的 Json
{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?请问如何确保该值作为 integer 传递? i appreciate the help.
我很感激帮助。
Found myself with this issue today!今天发现自己有这个问题!
You could use valueAsNumber
to get the value as a double您可以使用
valueAsNumber
将值作为双精度值
double
: Returns the value of the element, interpreted as one of the following, in order:double
:按顺序返回元素的值,解释为以下之一:
- A time value
时间价值
- A number
一个号码
NaN
if conversion is impossible如果无法进行转换,则为
NaN
source - MSN Web Docs
来源 - MSN Web 文档
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”类型 function 来处理输入,您可以将其更改为类似的内容(如果它不是数字,它将像正常一样将其分配为字符串):
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 :或者,如果您需要对转换进行更有限的控制,您可以执行类似于@bennygenel在他的回答中建议的操作:
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!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.