Ok, that was it.
The problem was that my Browser was setting the decimal separator as a dot (for example, 4.7
) and my backend was expecting a comma (for example, 4,7
) so that confused my application.
The culprit was what was posted on my second update, that was
var cultureInfo = new CultureInfo("es-CL");
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
I’m building a fruit and vegetables e-commerce app. I have made a system for users to add items to cart by entering values in an <input type="number">
field, within a form.
The problem I’m having is that when I enter “1.2” for example, my server receives the value “12”. But when I enter the value “1”, my server just receives the value “1”. This really bugs me. Does anyone know why this happens?
Thanks in advance.
Some data for context: my backend is build in Asp.Net Core 3.x. The backend endpoint looks like this:
[HttpPost]
public ActionResult UpdateShoppingCart(int productId, float amount)
{
Console.WriteLine(amount);
var selectedProduct = _productRepository.Products.SingleOrDefault(p => p.Id == productId);
float productCount = 0;
if(selectedProduct != null)
{
productCount = _shoppingCart.UpdateCart(selectedProduct, realAmount);
}
return Redirect(Request.Headers["Referer"].ToString());
}
The html part looks like this
<div class="text-center">
<div class="float-left">
<p>Cantidad:</p>
</div>
<div class="float-right">
<form method="post" class="form-inline" asp-controller="ShoppingCart" asp-action="UpdateShoppingCart">
<input type="hidden" name="productId" value="@Model.Product.Id"/>
<input name="amount" type="number" class="form-control h-auto input-add-to-cart" data-id="@Model.Product.Id" min=0 step="0.1" value="@(Model.ShoppingCartItem != null ? (Model.ShoppingCartItem.Amount).ToString(new CultureInfo("en-US")) : (0).ToString())"/>
<button type="submit" id="[email protected]" disabled class="ml-1 btn btn-sm btn-outline-warning"><i class="material-icons material-icons-actual-font" disabled>shopping_cart</i>Actualizar</button>
</form>
</div>
</div>
UPDATE:
The code for the ShoppingCartItem model is the following:
public class ShoppingCartItem
{
public int Id { get; set; }
public Product Product { get; set; }
public int ProductId { get; set; }
public float Amount { get; set; }
public string ShoppingCartId { get; set; }
}
SECOND UPDATE:
Could it be that i’m setting a culture in the thread that uses the comma as a dot?
In the Configure
method of Startup
, i’m setting
var cultureInfo = new CultureInfo("es-CL");
cultureInfo.NumberFormat.CurrencySymbol = "$";
CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;