ASP.NET MVC與Sql Server交互, 插入數據


 

在"ASP.NET MVC與Sql Server建立連接"中,與Sql Server建立了連接。本篇實踐向Sql Server中插入數據。

 

在數據庫幫助類中增加插入數據的方法。

 

   public class SqlDB
    {
        protected SqlConnection conn;
        //打開連接
        public bool OpenConnection()
        {
            conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
            try
            {
                bool result = true;
                if (conn.State.ToString() != "Open")
                {
                    conn.Open();
                }
                return result;
            }
            catch (SqlException ex)
            {
                return false;
            }
        }
        //關閉連接
        public bool CloseConnection()
        {
            try
            {
                conn.Close();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        //插入數據
        public int InsertData(string sql)
        {
            int lastId = 0;
            //string query = sql + ";SELECT @@Identity;";
            try
            {
                if(conn.State.ToString()=="Open")
                {
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    //cmd.ExecuteNonQuery();
                    lastId = ToInt(cmd.ExecuteScalar());//返回第一行的第一列
                }
                return ToInt(lastId);
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        //轉換成整型
        private int ToInt(object o)
        {
            try
            {
                return int.Parse(o.ToString());
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
    }

 

創建一個對應數據庫Product的視圖模型。   

 

    public class ProductVm
    {
        [Required(ErrorMessage="必填")]
        [StringLength(16)]
        public string Name { get; set; }
        [Required(ErrorMessage = "必填")]
        [StringLength(16)]
        public string Quantity { get; set; }
        [Required(ErrorMessage = "必填")]
        [StringLength(16)]
        public string Price { get; set; }
    }

 

在TestController中增加一個處理添加數據的2個Action。

 

    public class TestController : Controller
    {
        private SqlDB _db = new SqlDB();
        //
        // GET: /Test/
        public ActionResult Index()
        {
            bool r = _db.OpenConnection();
            if (r)
            {
                return Content("連接成功");
            }
            else
            {
                return Content("連接失敗");
            }
        }
        public ActionResult AddProduct()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddProduct(ProductVm productVm)
        {
            if(ModelState.IsValid)
            {
                _db.OpenConnection();
                int result = _db.InsertData("insert into Product(Name,quantity,Price) values('"+productVm.Name+"','"+productVm.Quantity+"','"+productVm.Price+"')");
                if(result > 0)
                {
                    ModelState.AddModelError("success", "創建成功");
                }
                else
                {
                    ModelState.AddModelError("error", "創建失敗");
                }
                _db.CloseConnection();
                return View();
            }
            else
            {
                return View(productVm);
            }
        }
    }

 

在對應的Test/AddProduct視圖中:

 

@model Portal.Models.ProductVm
@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>創建產品</h2>
@using (Html.BeginForm("AddProduct", "Test", new { @id = "addForm" }, FormMethod.Post))
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Quantity, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Quantity)
                @Html.ValidationMessageFor(model => model.Quantity)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Price, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Price)
                @Html.ValidationMessageFor(model => model.Price)
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="創建" class="btn btn-default" />
            </div>
        </div>
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM