skip to Main Content

I am making a mvc project and I am trying to do post the data but when I tried the post decimal number it isn’t sent right like this (I am writing 10.50 I am getting 1050 or writing 10,50 and it’s
stuck on validation and saying "The field UnitPrice must be a number.")

Here are some screenshots:

10.50

10,50

How can I send the data to database? I am using PostgreSQL and .Net 6.0. Here is my code:

Controller

 public ActionResult Add()
        {
            var model = new ProductAddViewModel
            {
                Product = new Product(),
                Categories = _categoryService.GetAll()
            };
            return View(model);
        }
        [HttpPost]
        public ActionResult Add(Product product)
        {
            if(ModelState.IsValid)
            {

                product.SupplierId = this.User.GetUserId();
                _productService.Add(product);
                TempData.Add("message", "Product was successfully added");
            }
            
            return RedirectToAction("Add");
        }

Product Class

    public class Product:IEntity
    {
        [Required]
        public int ProductId { get; set; }
        [Required]
        public string ProductName { get; set; }
        [Required]
        public int CategoryId { get; set; }
        [Required]
        //[Range(0.01, 999999999, ErrorMessage = "Price must be greater than 0.00")]
       // [DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
        public decimal UnitPrice { get; set; }
        [Required]
        [Range(0, Int32.MaxValue)]
        public int UnitsInStock { get; set; }
        [Required]
        public int UnitsOnOrder { get; set; }
        public string? SupplierId { get; set; }
        public string? ImageUrl { get; set; }
    }
}

ViewModel

    public class ProductAddViewModel
    {
        public Product Product { get; set; }
        public List<Category> Categories { get;  set; }
    }

Add.cshtml

@model Project.DataBase.MvcWebUI.Models.ProductAddViewModel
@{
    Layout = "~/Views/_AdminLayout.cshtml";
}
<h2>Add a product</h2>
<form asp-controller="Admin" asp-action="Add" method="post">
    <div class="mb-3">
        <label asp-for="Product.ProductName"></label>
        <input asp-for="Product.ProductName" class="form-control" placeholder="Product Name" />
        <span asp-validation-for="Product.ProductName"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Product.CategoryId"></label>
        <select asp-for="Product.CategoryId" class="form-control" 
        asp-items="@(new SelectList(Model.Categories,"CategoryId","CategoryName"))"></select>
        <span asp-validation-for="Product.CategoryId"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Product.UnitPrice"></label>
        <input asp-for="Product.UnitPrice" class="form-control" placeholder="Unit Price" />
        <span asp-validation-for="Product.UnitPrice"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Product.UnitsInStock"></label>
        <input asp-for="Product.UnitsInStock" class="form-control" placeholder="Units In Stock" />
        <span asp-validation-for="Product.UnitsInStock"></span>
    </div>
    <div class="mb-3">
        <label asp-for="Product.ImageUrl"></label>
        <input asp-for="Product.ImageUrl" class="form-control" placeholder="Image Url" />
        <span asp-validation-for="Product.ImageUrl"></span>
    </div>
    <input type="submit" value="Add" class="btn btn-sm btn-success" />
</form>

Database

CREATE TABLE Products(
    "ProductId" serial PRIMARY KEY NOT NULL,
    "ProductName" character varying(15) NOT NULL,
    "CategoryId" smallint not null,
    "SupplierId" text NOT NULL,
    "UnitPrice" numeric NOT NULL,
    "UnitsInStock" SMALLINT NOT NULL,
    "UnitsOnOrder" SMALLINT,
    "ImageUrl" text
);

2

Answers


  1. Well, based on your code snippet, it’s clear that you have done two major mistakes. First of all, you have not defined the decimal precision for your UnitPrice property and the other one in database schema entity definition is incorrect. You should update your code in following way:

    Asp.net core POCO Model:

        [Required]
        [Column(TypeName = "decimal(18, 2)")] // OR `[Precision(18, 2)]`
        public decimal UnitPrice { get; set; }
    

    Note: this means UnitPrice would be a decimal number which would contains upto 18 main number along with 2 decimal precision after . point. Keep in mind that [Column(TypeName = "decimal(18, 2)")] and [Precision(14, 2)] act same. More details can be found in the official document here.

    Database Schema:

    UnitPrice NUMERIC(18,2) NOT NULL
    

    Note: Now PostgreSQL schema, would preserve up to 18 main number along with 2 decimal precision. You could check official document for more information.

    The above two reasons are causing your unexpected decimal result.

    Login or Signup to reply.
  2. Looks like you are saving UnitPrice as a number, not exactly a decimal value.

    Drop your table and create again modifying UnitPrice as "UnitPrice" decimal(18,2) NOT NULL.

    CREATE TABLE Products(
        "ProductId" serial PRIMARY KEY NOT NULL,
        "ProductName" character varying(15) NOT NULL,
        "CategoryId" smallint not null,
        "SupplierId" text NOT NULL,
        "UnitPrice" decimal(18,2) NOT NULL,
        "UnitsInStock" SMALLINT NOT NULL,
        "UnitsOnOrder" SMALLINT,
        "ImageUrl" text
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search