【问题标题】:asp.net mvc / Sql double registerasp.net mvc / Sql 双寄存器
【发布时间】:2016-02-08 07:04:42
【问题描述】:

我创建了一个新的 MVC 项目,并在 db 中创建了插入函数。我的问题是,当我将模型输入数据库时​​,它会记录两次。尝试调试,但遗憾的是找不到错误。下面的代码有遗漏吗?

 public class DbCode
    {
        protected SqlConnection conn;

        public bool Open(string Connection = "MyDb")
        {
            conn = new SqlConnection(@WebConfigurationManager.ConnectionStrings[Connection].ToString());
            try
            {
                var b = true;
                if (conn.State.ToString() != "Open")
                {
                    conn.Open();
                }
                return b;
            }
            catch (SqlException ex)
            {
                return false;
            }
        }

        public bool Close()
        {
            try
            {
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public int ToInt(object s)
        {
            try
            {
                return Int32.Parse(s.ToString());
            }
            catch (Exception)
            {
                return 0;
            }

        }

        public int DataInsert(string sql)
        {
            int LastID = 0;
            string query = sql + ";SELECT @@Identity;";
            try
            {
                if (conn.State.ToString() == "Open")
                {
                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.ExecuteNonQuery();
                    LastID = this.ToInt(cmd.ExecuteScalar());
                }
                return this.ToInt(LastID);
            }
            catch
            {
                return 0;
            }
        }
    }


 public class StudentModel
    {
        [Required]
        [StringLength(5)]
        public string productname { get; set; }

        [Required]
        [StringLength(5)]
        public string quantity { get; set; }

        [Required]
        [StringLength(5)]
        public string price { get; set; }
    }

控制器

 public class StudentController : Controller
    {
        protected DbCode DB = new DbCode();
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SaveDataStudent(StudentModel student)
        {
            if (ModelState.IsValid)
            {
                DB.Open();
                int i = DB.DataInsert("INSERT INTO tblproducts(productname,quantity,price) VALUES('" + student.productname + "','" + student.quantity + "','" + student.price + "')");
                if (i > 0)
                {
                    ModelState.AddModelError("Success", "Save Success");
                }
                else
                {
                    ModelState.AddModelError("Error", "Save Error");
                }
                DB.Close();
            }
            return RedirectToAction("Index", "Student");
        }
    }

学生观

@model MVC5.Models.StudentModel

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm("SaveDataStudent", "Student", new { @id = "Form" }, FormMethod.Post))
{
    @Html.ValidationSummary();
    @Html.AntiForgeryToken();
    @Html.LabelFor(m => m.productname);
    @Html.TextBoxFor(m => m.productname);<br/>

    @Html.LabelFor(m => m.quantity);
    @Html.TextBoxFor(m => m.quantity);<br />

    @Html.LabelFor(m => m.price);
    @Html.TextBoxFor(m => m.price);<br />

    <input type="submit" value="Save" name="Save" />
}

在 webconfig 中添加了连接字符串

【问题讨论】:

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


    【解决方案1】:

    问题在于以下几行:

    cmd.ExecuteNonQuery();
    LastID = this.ToInt(cmd.ExecuteScalar());
    

    您执行相同的命令两次,因此将 2 条记录插入到数据库中。

    为了读取最后一个标识值,我将定义一个存储过程,它将数据插入表中,然后返回最后一个标识值。这种方法被描述为here

    顺便说一句,您的代码还有另一个严重的问题。您可以通过连接字符串来定义 sql 命令。其中一些字符串来自用户端。这意味着您的代码容易受到 SQL 注入攻击。相反,您应该使用参数(参见thisthis)。

    我还建议不要使用像 conn.State.ToString() == "Open" 这一行这样的魔法常量,更好的方法是使用枚举成员:conn.State == ConnectionState.Open

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多