在"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. springcloud Zuul中路由配置细节

    上篇文章我们介绍了API网关的基本构建方式以及请求过滤,小伙伴们对Zuul的作用应该已经有了一个基本的认识,但是对于路由的配置我们只是做了一个简单的介绍,本文我们就来看看路由配置的其他一些细节. 首先 ...

  2. 012_iTerm2 快捷键大全

    标签 新建标签:command + t 关闭标签:command + w 切换标签:command + 数字 command + 左右方向键 切换全屏:command + enter 查找:comma ...

  3. 基于Apache在本地配置多个虚拟主机站点

    简单的说,打开httpd.conf 在最后加入如下内容: <VirtualHost 127.0.0.2:80>    DocumentRoot d:/AppServ/www2    Ser ...

  4. java虚拟机规范(se8)——java虚拟机结构(一)

    本文翻译自:https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html 第二章 虚拟机结构 本文档描述了一个抽象的虚拟机规范,并不描述 ...

  5. 【前端vue开发】vue知识点超链接学习笔记

    1.如何去除vue项目中的 # --- History模式: https://www.cnblogs.com/zhuzhenwei918/p/6892066.html 2.三分钟教你写个Vue组件: ...

  6. JavaScript如何获得input元素value值

    转载地址:http://aquarius-zf.iteye.com/blog/605144 在页面中我们最常见的页面元素就是input了,但是我们如何用JavaScript得到网页input中输入的v ...

  7. 有关redis相关的性能优化及内存说明

    本篇文章不涉及redis的安装配置,百度或谷歌即可,很简单. 首先,我来说说redis的应用场景,大部分公司都是将redis作为缓存服务器,或者作为ELK日志收集里面的缓存角色(其他这里就不做介绍,比 ...

  8. 使用libvirt管理KVM(一)

    一. 安装和配置libvirt,源码下载http://www.qemu-project.org/download/#source. 二. 从包和源码包进行安装libvirt. 1. 在ubuntu系统 ...

  9. Python3之turtle模块的使用

    Python3之turtle模块的使用     直接扣代码就行: import turtle as t t.pensize(4) t.hideturtle() t.colormode(255) t.c ...

  10. SpringBoot与SpringCloud学习指南

    推荐一个Spring Boot的导航网站:Spring Boot 中文导航 Spring boot使用的各种示例,以最简单.最实用为标准 spring-boot-helloWorld:spring-b ...