在"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>


ASP.NET MVC与Sql Server交互, 插入数据的更多相关文章

  1. ASP.NET MVC与Sql Server交互,把字典数据插入数据库

    在"ASP.NET MVC与Sql Server交互, 插入数据"中,在Controller中拼接sql语句.比如: _db.InsertData("insert int ...

  2. Incorporating ASP.NET MVC and SQL Server Reporting Services, Part 2

    In the last issue, I introduced you to the basics of incorporating SQL Server Reporting Services int ...

  3. SQL Server 批量插入数据的两种方法

    在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍 SQL Server支持的两种批 ...

  4. SQL Server 批量插入数据的两种方法(转)

    此文原创自CSDN TJVictor专栏:http://blog.csdn.net/tjvictor/archive/2009/07/18/4360030.aspx 在SQL Server 中插入一条 ...

  5. 转:SQL Server 批量插入数据的两种方法

    在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍SQL Server支持的两种批量 ...

  6. Incorporating ASP.NET MVC and SQL Server Reporting Services, Part 1

    Your ASP.NET MVC application needs reports. What do you do? In this article, I will demonstrate how ...

  7. ASP.NET MVC与Sql Server建立连接

    用惯了使用Entity Framework连接数据库,本篇就来体验使用SqlConnection连接数据库. 打开Sql Server 2008,创建数据库,创建如下表: create table P ...

  8. asp.net mvc entityframework sql server 迁移至 mysql方法以及遇到的问题

    背景: 我原来的项目是asp.net mvc5 + entityframework 6.4 for sql server(localdb,sql server),现在需要把数据库切换成mysql,理论 ...

  9. SQL Server返回插入数据的ID和受影响的行数

    首先看看数据库里面的数据(S_Id为自增长标识列): sql server 中返回上一次插入数据的ID(标识值)有三种方式: 第一种 @@IDENTITY: insert into Student(S ...

随机推荐

  1. 网易与Google合作发布开源UI自动化测试方案 牛逼:Google 方面评价,这可能是目前世界上最好的 Android 游戏自动化测试方案。

    美西时间 3 月 19 日,在 GDC 开幕第一天的 Google 开发者专场,Google 发布了一款由网易研发的 UI 自动化测试方案:Airtest Project.Google 方面评价,这可 ...

  2. 原生js实现ajax跨域(兼容IE8,IE9)

    html设置meta标签兼容360兼容模式和IE怪异模式 <meta http-equiv="X-UA-Compatible" content="IE=9;IE=8 ...

  3. Linux 生产实习01

    Linux 生产实习01 标签(空格分隔): Linux 2018.07.02 相关软件下载地址:Linux Study 0x01. 安装 VMware Workstation VMware Work ...

  4. CF1063A 【Oh Those Palindromes】

    考虑在一个部分串中加入字符使得最终构造的串回文子串最多的方案 考虑简单情况,对于只含一种元素的串,我们要插入其他元素 记原有元素为$a$,新加元素为$b$ 考虑$b$的最优插入位置 原串$aaaa.. ...

  5. sysbench安装及性能测试

    现在的压力测试工具各种各样,只要上手好几款功能强大点的而且比较大众化的压力测试工具即可,以下跟大家交流下sysbench的安装和压力测试 sysbench支持以下几种测试模式: 1.CPU运算性能 2 ...

  6. linux pwd指令C实现

    linux pwd指令C实现 研究实现pwd所需的系统调用 我们可以通过man命令和grep命令来获取我们所需要的系统调用函数信息 man chdir Linux pwd命令用于显示工作目录. 执行p ...

  7. 慢查询日志和profiling

    MySQL调优三步: 慢查询 (分析出现出问题的sql) Explain (显示了mysql如何使用索引来处理select语句以及连接表.可以帮助选择更好的索引和写出更优化的查询语句) Profile ...

  8. Java之路(四)数组初始化

    本文主要讲数组的初始化方法.可变参数列表以及可变参数列表对函数重载的影响. 1.数组初始化 定义数组的方式: int[] arr1; 或  int arr1[]; 数组初始化 通过上边的定义,我们只是 ...

  9. 002.NTP服务端搭建

    一 安装及准备 1.1 安装NTP [root@server ~]# yum -y install ntp #也可下载之后rpm安装,或者源码安装 1.2 NTP服务地址 http://www.ntp ...

  10. 关于Sql Server的一些知识点的定义总结

    数据库完整性:是指数据库中数据在逻辑上的一致性.正确性.有效性和相容性 实体完整性(Entity Integrity  行完整性):实体完整性指表中行的完整性.主要用于保证操作的数据(记录)非空.唯一 ...