【问题标题】:How to solve the bug the zero is inserted in database even i insert the number value in textboxfor in asp.net mvc?即使我在asp.net mvc的textboxfor中插入数字值,如何解决在数据库中插入零的错误?
【发布时间】:2022-01-25 06:08:16
【问题描述】:

在这里,我开发了代码,当用户单击“购买”按钮时,将使用该数据打开新视图。现在数据是在文本框中获取的,因为我想插入相同的数据,但是 ProductName 被完美地插入,但是每次产品的价格都为零,即使在文本框中,实际价格也是可见的,但也存在错误 我想用实际数据插入 ProductName 和 Price 下面的代码是:

型号

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" class="logo">
       <div class="icon">Medcart</div>
       <div class="search_box">
               <input type="search" placeholder="Search here">
               <span class="fa fa-search"></span>
       </div>
       <ol>
            <li><a href="#">Login</a> </li>
           <li><a href="#">Signup</a> </li>
       </ol>
     </nav>
      <div class="cards_wrap">
      @foreach (var item in Model)
    {
        <div class="card_item">
            <div class="card_inner">
                <img src="~/images/p2.jpeg" />
                <div class="role_name">@Html.DisplayFor(modelItem => item.ProductName)</div>
                <div class="real_name"><strong>@Html.DisplayFor(modelItem => item.Price)</strong></div>
                <div class="film">
                    "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 class="form-horizontal">
            <h4>Purchase</h4>
            <hr />
            <div class="form-group">
                <label class="control-label col-md-2">Product Name</label>
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })
                    
                </div>
            </div>
    
            <div class="form-group">
                <label class="control-label col-md-2">Price</label>
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Check Out" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

模型中的 PharmaContext 文件

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

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    也许你应该这样做:

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

    如果您使用的是 MVC- 1.5 或更高版本,则不需要使用 htmlAttributes,但您应该更改 textBoxFor 的输入值类型,因为它始终是您传递给 int 参数的字符串

    【讨论】:

      【解决方案2】:

      代码中存在错误。视图使用模型

      @model PharmaProj.Models.Product
      

      但是您将产品从视图提交到采购是输入参数的操作

      [HttpPost]
       public ActionResult PurchaseProd(Purchase po)
      

      你必须决定使用什么产品或购买

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-25
        • 2013-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-05-02
        • 2020-12-22
        • 1970-01-01
        相关资源
        最近更新 更多