Asp.net mvc / sql double register

I created a new MVC project and I made the insert function in db. My problem is that when I enter the model in db, it writes twice. I tried to debug, but, unfortunately, could not find the error. Is there a flaw in the code below?

 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; }
    }

controller

 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");
        }
    }

Student viewing

@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" />
}

Added connection string in webconfig

+4
source share
1 answer

The problem lies in these lines:

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

You execute the same command twice, so 2 records are inserted into the database.

, , , . .

, . sql . . , SQL Injection. (. this this).

, conn.State.ToString() == "Open". : conn.State == ConnectionState.Open.

+1

Source: https://habr.com/ru/post/1627734/


All Articles