Home > Back-end >  How to solve the bug the zero is inserted in database even i insert the number value in textboxfor i
How to solve the bug the zero is inserted in database even i insert the number value in textboxfor i

Time:12-25

Here I develop the code in which when user click on Buy button the new view open with that Data. Now the data is fetch in textboxfor I want to insert the same data but the ProductName is inserted perfectly but each and every time price of the product is zero even in textbox the actual price is visible but than also bug is there I want to insert the ProductName and Price both with actual data Here below the code is:

Model

public class Purchase
{
    [Key]
    public int purID { get; set; }
    public string productName { get; set; }
    public int productPrice { get; set; }
    public string customerEmail { get; set; }
    
}

Index.cshtml

    @model IEnumerable<PharmaProj.Models.Product>
    @{
      Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
         <meta name="viewport" content="width=device-width" />
         <meta http-equiv='cache-control' content='no-cache'>
         <meta http-equiv='expires' content='0'>
         <meta http-equiv='pragma' content='no-cache'>
         <link href="~/Content/HomePage.css" rel="stylesheet" type="text/css"/>
         <title>Index</title>
      </head>
      <body>
      @Html.Raw(TempData["ProdInOrderMsg"])
      <nav>
       <img src="logo.png" >
       <div >Medcart</div>
       <div >
               <input type="search" placeholder="Search here">
               <span ></span>
       </div>
       <ol>
            <li><a href="#">Login</a> </li>
           <li><a href="#">Signup</a> </li>
       </ol>
     </nav>
      <div >
      @foreach (var item in Model)
    {
        <div >
            <div >
                <img src="~/images/p2.jpeg" />
                <div >@Html.DisplayFor(modelItem => item.ProductName)</div>
                <div ><strong>@Html.DisplayFor(modelItem => item.Price)</strong></div>
                <div >
                    "Lorem ipsum dolor sit amet, consectetur adipiscing elit,
                    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
                </div>
                @Html.ActionLink("Buy", "PurchaseProd", new { id = item.ProductID })
            </div>
        </div>
    }
</div>
</body>
</html>

HomeController

// GET: Home
        public ActionResult Index()
        {
            PharmaContext pcontext = new PharmaContext();
            List<Product> all_prod_fetch = pcontext.GetProducts();
            return View(all_prod_fetch);
        }
        public ActionResult PurchaseProd(int id)
        {
            PharmaContext pcontext = new PharmaContext();
            var show_prod_row = pcontext.GetProducts().Find(model => model.ProductID == id);
            return View(show_prod_row);
        }
        [HttpPost]
        public ActionResult PurchaseProd(Purchase po)
        {
            try
            {
                if(ModelState.IsValid == true)
                {
                    PharmaContext pcontext = new PharmaContext();
                    bool checkProdInOrder = pcontext.AddProdinOrder(po);
                    if(checkProdInOrder == true)
                    {
                        TempData["ProdInOrderMsg"] = "<script>alert('You order is placed successfully')</script>";
                        return RedirectToAction("Index");
                    }
                }
                return View();
            }
            catch
            {
                return View();
            }
        }

PurchaseProd.cshtml

@model PharmaProj.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>PurchaseProd</title>
</head>
<body>
    @using (Html.BeginForm("PurchaseProd", "Home",FormMethod.Post))
    {
        @Html.AntiForgeryToken()

        @Html.HiddenFor(model => model.ProductID)
        
        <div >
            <h4>Purchase</h4>
            <hr />
            <div >
                <label >Product Name</label>
                <div >
                    @Html.TextBoxFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })
                    
                </div>
            </div>
    
            <div >
                <label >Price</label>
                <div >
                    @Html.TextBoxFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                </div>
            </div>
    
            <div >
                <div >
                    <input type="submit" value="Check Out"  />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

PharmaContext file in Model

public List<Product> GetProducts()
        {
            List<Product> ProductList = new List<Product>();
            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand("spGetProducts", con);
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Product p = new Product();
                p.ProductID = Convert.ToInt32(dr.GetValue(0).ToString());
                p.ProductName = dr.GetValue(1).ToString();
                p.Price = (int)Convert.ToInt64(dr.GetValue(2).ToString());

                p.Count = Convert.ToInt32(dr.GetValue(3).ToString());
                ProductList.Add(p);
            }
            con.Close();
            return ProductList;
        }
public bool AddProdinOrder(Purchase po)
        {
            SqlConnection con = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand("AddOrder", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@productname", po.productName);
            cmd.Parameters.AddWithValue("@productprice", po.productPrice);
            con.Open();
            int i = cmd.ExecuteNonQuery();
            con.Close();

            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

PurchaseProd Output

Debug when i click on CheckOut button

Database

CodePudding user response:

Probably You should do This:

@Html.TextBoxFor(model => model.Price, new { type = number } )

If You are using MVC- 1.5 or higher you dont need to use htmlAttributes, but you should change the type of input value for the textBoxFor cause its always a string that you are passing to your int parameter

CodePudding user response:

There is a bug in the code. The view uses a model

@model PharmaProj.Models.Product

but you submit Product from view to the action where Purchace is an input parameter

[HttpPost]
 public ActionResult PurchaseProd(Purchase po)

you have to decide what to use Product or Purchase

  • Related