如何在Controller动作中引用Html.TextBoxFor值(在asp.net-mvc中更新表)

时间:2019-01-26 05:09:08

标签: c# sql-server asp.net-mvc

我正在创建一个销售Web应用程序。输入销售量后,我想更新库存剩余数量。我为文本框设置了ID,并在查询中使用了文本框ID。我相信做错了。

请在下面查看我的“视图”和“模型”代码(我将不胜感激有关如何执行此操作的其他想法)。

我的查看代码:

<div class="container" style="width:40%; margin-top:2%">
@using (Html.BeginForm("SaveSales", "Sales", FormMethod.Post))
{

    @Html.DropDownListFor(model => model.Prod_id, ViewBag.SalesName as        SelectList, "--Select Product--", new { id = "ProdIds", @class = "form-control"        })
    <br />
    @Html.TextBoxFor(model => model.Unit_purchase, new { id = "quant", @class = "form-control", @placeholder = "Amount Purchase" })
    <br />
    @Html.TextBoxFor(model => model.Unit_price, new { @class = "form-control", @placeholder = "Unit Price" })
    <br />
    @Html.DropDownListFor(model =>model.Emp_id, ViewBag.EmpName as SelectList, "--select Employee--", new { @class = "form-control" })
    <br />
    //@Html.TextAreaFor(model => model.Dates, new{@placeholder = "Date", @type = "date", @Value = Model.Dates.ToString("yyyy-MM-dd") })
    @Html.EditorFor(model => model.Dates, new { @type = "date" })
    <br />
    <br />

    @Html.DropDownListFor(model => model.Cust_id, ViewBag.CustName as SelectList, "--Select Customer--", new { @class = "form-control" })
    <br />
    <input type="Submit" value=" Submit" />  <input type="reset" value=" Reset" />
}
 </div>

我的控制器代码(更新查询代码始于----使用(SqlConnection……)

    namespace Salesapp.Controllers
     {
     public class SalesController : Controller
      {
        // GET: Sales
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult SalesIndex()
        {
            SalesLayanEntities3 db = new SalesLayanEntities3();
            List<Product> list = db.Products.ToList();
            ViewBag.SalesName = new SelectList(list, "prod_id", "prod_name");

            List<Employee> listi = db.Employees.ToList();
            ViewBag.EmpName = new SelectList(listi, "emp_id", "emp_name");


            List<Customer> listiw = db.Customers.ToList();
            ViewBag.CustName = new SelectList(listiw, "cust_id", "cust_name");

            return View();
        }

        public ActionResult SaveSales(SalesForm model)
        {
            try
            {
                SalesLayanEntities3 db = new SalesLayanEntities3();
                Sales_Record sale_prod = new Sales_Record();

                sale_prod.unit_price = model.Unit_purchase;
                sale_prod.unit_purchase = model.Unit_price;
                sale_prod.prod_id = model.Prod_id;
                sale_prod.emp_id = model.Emp_id;
                sale_prod.Dates = model.Dates;
                sale_prod.cust_id = model.Cust_id;

                db.Sales_Record.Add(sale_prod);
                db.SaveChanges();
                int latestProdId = sale_prod.sales_id;
                TempData["status"] = "Success";

                using (SqlConnection sqlCon = new SqlConnection(@"Data Source=servername;Initial Catalog=SalesLayan;User ID=username;Password=mypassword;"))
                {
                    sqlCon.Open();
                    SqlCommand cmd12 = sqlCon.CreateCommand();
                    cmd12.CommandType = CommandType.Text;
                    cmd12.CommandText = "update product set prod_quantity=prod_quantity-" + quant.Text "where prod_id=" + ProdIds.Text;
                    cmd12.ExecuteNonQuery();
                }

            }

            catch (Exception ex)
            {
                throw ex;


            }
            return RedirectToAction("SalesIndex");
        }
    }  
}

2 个答案:

答案 0 :(得分:1)

查看本节:

using (SqlConnection sqlCon = new SqlConnection(@"Data Source=servername;Initial Catalog=SalesLayan;User ID=username;Password=mypassword;"))
{
    sqlCon.Open();
    SqlCommand cmd12 = sqlCon.CreateCommand();
    cmd12.CommandType = CommandType.Text;
    cmd12.CommandText = "update product set prod_quantity=prod_quantity-" + quant.Text "where prod_id=" + ProdIds.Text;
    cmd12.ExecuteNonQuery();
}

改为这样做,以避免sql注入问题并提高性能:

string sql = "update product set prod_quantity=prod_quantity- @sold_quantity where prod_id= @Prod_ID";
using (var sqlCon = new SqlConnection(@"Data Source=servername;Initial Catalog=SalesLayan;User ID=username;Password=mypassword;"))
using (var cmd = new SqlCommand(sql, sqlCon))
{
    //Have to guess at types and lengths here. Use actual types and lengths from the database
    cmd.Parameters.Add("@sold_quantity", SqlDbType.Int).Value = int.Parse(quant.Text);
    cmd.Parameters.Add("@Prod_ID", SqlDbType.Int).Value = int.Parse(ProdIds.Text);
    sqlCon.Open();
    cmd12.ExecuteNonQuery();
}

答案 1 :(得分:0)

在您的查询中,对于要从库存中扣除的数量,变量引用可能不正确。

cmd12.CommandText = "update product set prod_quantity=prod_quantity-" + quant.Text "where prod_id=" + ProdIds.Text;

quant.Text上方的那一行可能是错误的变量引用。

quant.Text可能需要为sale_prod.unit_pricemodel.Unit_purchase

您的sql命令正在设置prod_quantity = prod_quantity - quant.Text

但是quant.Text方法中没有变量SaveSales

使用Helper TextBox时,它使用模型名称作为输入字段名称:

示例:Razor视图中的TextBoxFor()

@model Student

@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })  

HTML结果:

<input class="form-control" 
        id="StudentName" 
        name="StudentName" 
        type="text" 
        value="John" />
  

TextBoxFor

     

TextBoxFor辅助方法是一种强类型的扩展方法。它为使用lambda表达式指定的模型属性生成文本输入元素。 TextBoxFor方法将指定的模型对象属性绑定到输入文本。因此,它会自动在文本框中显示模型属性的值,反之亦然。

参考:

将表单发回时,.NET MVC使用所谓的“模型绑定”将表单值组合为Action参数类型:

  

ASP.NET MVC模型绑定允许您将HTTP请求数据与模型进行映射。它是使用浏览器在HTTP请求中发送的数据创建.NET对象的过程。刚接触ASP.Net MVC的ASP.NET Web Forms开发人员大多感到困惑,当View的值到达Controller类的Action方法时如何将其转换为Model类,因此这种转换是由Model绑定器完成的。

参考

相对于Joel's注释,将参数传递给sql语句以使用SqlParameters的最佳做法是,如以下示例所示:

  
// 1. declare command object with parameter
  SqlCommand cmd = new SqlCommand(
      "select * from Customers where city = @City", conn);

使用参数化的sql命令将有助于防止sql注入攻击。好的做法还应该是过滤和验证用户输入,因为您在sql update命令中使用了它。

参考