【小白入门】ASP.NET MVC +BootStrap实现增删查改(CURD)

作为一个学习了两年的.net Codeer毕业之后就一直没有asp.net开发,因为面向小白,面向平时上课听个大概的同学,如果你完全零基础 ,可能不会看得太懂。

首先,我们需要封装一个数据访问层对数据库进行操作。

public class DB
    {
        //数据库连接字符串
        public static string connString = ConfigurationManager.ConnectionStrings["Model1"].ConnectionString;
        //定义数据库连接对象
        public static SqlConnection conn = new SqlConnection(connString);

        // 查询,获取数据
        public static DataTable GetDataTable(string sqlStr)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                SqlDataAdapter dapt = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                dapt.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                //return null;
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        // 增删改
        public static bool ExcuteCommand(string sqlStr)
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sqlStr, conn);
                //conn.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception ex)
            {
                //return false;
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }

    }

以上代码未防止SQL注入。

 

首先,来看视图层学生新增代码:

@{
    ViewBag.Title = "StuAdd";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}

<form method="post">
    <input type="hidden" name="stuNo" class="form-control" value="@ViewBag.stuNo" id="input1" placeholder="请输入学号">

    <div class="form-group">
        <label for="input2">姓名</label>
        <input type="text" name="name" class="form-control" value="@ViewBag.name" id="input2" placeholder="请输入姓名">
    </div>
    <div class="form-group">
        <label for="input22">密码</label>
        <input type="password" name="pwd" class="form-control" value="@ViewBag.pwd" id="input22" placeholder="请输入密码">
    </div>
    <div class="form-group">
        <label for="input3">性别</label>
        <select name="gender">
            @if (ViewBag.gender == "男")
            {
                <option value="男" selected>男</option>
                <option value="女">女</option>
            }
            else
            {
                <option value="男">男</option>
                <option value="女" selected>女</option>
            }
        </select>
    </div>
    <div class="form-group">
        <label for="input4">学院</label>
        <input type="text" name="college" class="form-control" value="@ViewBag.college" id="input4" placeholder="请输入学院">
    </div>
    <div class="form-group">
        <label for="input5">专业</label>
        <input type="text" name="prof" class="form-control" value="@ViewBag.prof" id="input5" placeholder="请输入专业">
    </div>
    <div class="form-group">
        <label for="input6">班级</label>
        <input type="text" name="className" class="form-control" value="@ViewBag.className" id="input6" placeholder="请输入班级">
    </div>
    <div class="form-group">
        <label for="input7">联系方式</label>
        <input type="tel" name="tel" class="form-control" value="@ViewBag.tel" id="input7" maxlength="11" minlength="11" placeholder="请输入联系方式">
    </div>
    <button type="submit" class="btn btn-primary">提交</button>
</form>

视图层大致就是一个form表单,表单会默认提交到当前网址。

我们来看下,Controller控制器部分的代码,控制器的方法页面显示部分默认是接受get请求的,接受表单数据的方法必须使用[httpPost]修饰,接受post方式传过来的表单数据,表单也必须指定post方式。

        // 学生-新增
        [HttpGet]
        public ActionResult StuAdd()
        {
            return View();
        }
        // 学生-新增
        [HttpPost]
        public ActionResult StuAdd(stu u)
        {
            string sql = "insert into stu (name,pwd,gender,college,prof,className,tel) values ('" + u.name + "','"+u.pwd+"','" + u.gender + "','" + u.college + "','" + u.prof + "','" + u.className + "','" + u.tel + "')";
            if (DB.ExcuteCommand(sql))
            {
                Response.Write("<script type='text/javascript'>alert('添加成功!');window.location.href='/Admin/Stu';</script>");
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('添加失败!');window.location.href='/Admin/StuAdd';</script>");
            }
            return View();
        }

视图层首页:


@{
    ViewBag.Title = "Stu";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}

<div class="container-fluid">
    <div class="row">
        <a href="/Admin/StuAdd" class="btn btn-primary">新增</a>
    </div>
</div>

<div class="container-fluid">
    <div class="row">
        <form class="form-inline" method="get">
            <div class="form-group">
                <label for="exampleInputName2">请输入姓名:</label>
                <input type="text" class="form-control" id="exampleInputName2" name="content" placeholder="请输入关键词">
            </div>
            <button type="submit" class="btn btn-info">搜索</button>
        </form>
    </div>
</div>

<table class="table table-striped">
    <thead>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>学院</th>
            <th>专业</th>
            <th>班级</th>
            <th>联系方式</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @{
            System.Data.DataTable dt = ViewBag.data;
            if (dt != null)
            {
                foreach (System.Data.DataRow row in dt.Rows)
                {
                    <tr>
                        <th scope="row">@row["stuNo"].ToString()</th>
                        <td>@row["name"].ToString()</td>
                        <td>@row["gender"].ToString()</td>
                        <td>@row["college"].ToString()</td>
                        <td>@row["prof"].ToString()</td>
                        <td>@row["className"].ToString()</td>
                        <td>@row["tel"].ToString()</td>
                        <td>
                            <a href="/Admin/StuEdit?stuNo=@row["stuNo"].ToString()" class="btn btn-info">编辑</a>
                            <a href="" onclick="javascript:del(@row["stuNo"].ToString());" class="btn btn-danger">删除</a>
                        </td>
                    </tr>
                }
            }
        }
    </tbody>
</table>
<script>
    function del(stuNo) {
        var msg = "你真的确定要删除吗?\n\n请确认!";
        if (confirm(msg) == true) {
            window.location.href = "/Admin/StuDel?stuNo=" + stuNo;
            window.event.returnValue = false;
        }
        return false;
    }
</script>

视图层增加/修改页面:

@{
    ViewBag.Title = "StuAdd";
    Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}

<form method="post">
    @*<div class="form-group">
            <label for="input1">学号</label>
            <input type="text" name="stuNo" class="form-control" id="input1" placeholder="请输入学号">
        </div>*@
    <input type="hidden" name="stuNo" class="form-control" value="@ViewBag.stuNo"  id="input1" placeholder="请输入学号">

    <div class="form-group">
        <label for="input2">姓名</label>
        <input type="text" name="name" class="form-control" value="@ViewBag.name"  id="input2" placeholder="请输入姓名">
    </div>
    <div class="form-group">
        <label for="input3">性别</label>
        <select name="gender">
            @if (ViewBag.gender == "男")
            {
                <option value="男" selected>男</option>
                <option value="女">女</option>
            }
            else
            {
                <option value="男">男</option>
                <option value="女" selected>女</option>
            }
        </select>
    </div>
    <div class="form-group">
        <label for="input4">学院</label>
        <input type="text" name="college" class="form-control" value="@ViewBag.college" id="input4" placeholder="请输入学院">
    </div>
    <div class="form-group">
        <label for="input5">专业</label>
        <input type="text" name="prof" class="form-control" value="@ViewBag.prof" id="input5" placeholder="请输入专业">
    </div>
    <div class="form-group">
        <label for="input6">班级</label>
        <input type="text" name="className" class="form-control" value="@ViewBag.className" id="input6" placeholder="请输入班级">
    </div>
    <div class="form-group">
        <label for="input7">联系方式</label>
        <input type="tel" name="tel" class="form-control" value="@ViewBag.tel" id="input7" maxlength="11" minlength="11" placeholder="请输入联系方式">
    </div>
    <button type="submit" class="btn btn-primary">提交</button>
</form>

 

控制器代码:

using ExamWebSystem.DAL;
using ExamWebSystem.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ExamWebSystem.Controllers
{
    public class AdminController : Controller
    {
        // GET: Admin
        public ActionResult Index()
        {
            return View();
        }
        // 学生管理首页
        public ActionResult Stu(string content)
        {
            if(content == "")
            {
                string sql = "select * from stu order by stuNo desc";
                DataTable dt = DB.GetDataTable(sql);
                ViewBag.data = dt;
            }
            else
            {
                string sql = "select * from stu where name like '%"+content+ "%' order by stuNo desc";
                DataTable dt = DB.GetDataTable(sql);
                ViewBag.data = dt;
            }

            return View();
        }
        // 学生-新增
        [HttpGet]
        public ActionResult StuAdd()
        {
            return View();
        }
        // 学生-新增
        [HttpPost]
        //string stuNo,string name,string gender,string college,string prof,string className,string tel
        public ActionResult StuAdd(stu u)
        {
            string sql = "insert into stu (name,gender,college,prof,className,tel) values ('" + u.name + "','" + u.gender + "','" + u.college + "','" + u.prof + "','" + u.className + "','" + u.tel + "')";
            if (DB.ExcuteCommand(sql))
            {
                Response.Write("<script type='text/javascript'>alert('添加成功!');window.location.href='/Admin/Stu';</script>");
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('添加失败!');window.location.href='/Admin/StuAdd';</script>");
            }
            return View();
        }
        // 学生-编辑
        [HttpGet]
        public ActionResult StuEdit(string stuNo) 
        {
            string sql = "select * from stu where stuNo = "+stuNo+" order by stuNo desc";
            DataTable dt = DB.GetDataTable(sql);

            if (dt.Rows.Count == 1)
            {
                ViewBag.stuNo = int.Parse(dt.Rows[0]["stuNo"].ToString());
                ViewBag.name = dt.Rows[0]["name"].ToString();
                ViewBag.gender = dt.Rows[0]["gender"].ToString();
                ViewBag.college = dt.Rows[0]["college"].ToString();
                ViewBag.prof = dt.Rows[0]["prof"].ToString();
                ViewBag.className = dt.Rows[0]["className"].ToString();
                ViewBag.tel = dt.Rows[0]["tel"].ToString();
            }
            else
            {
                ViewBag.stuNo = -1;
                ViewBag.name = string.Empty;
                ViewBag.gender = string.Empty;
                ViewBag.college = string.Empty;
                ViewBag.prof = string.Empty;
                ViewBag.className = string.Empty;
                ViewBag.tel = string.Empty;
            }
            return View("StuAdd");
        }
        // 学生-编辑
        [HttpPost]
        public ActionResult StuEdit(stu u)
        {
            string sql = "update stu set name='"+u.name+ "',gender='" + u.gender + "',college='" + u.college + "',prof='" + u.prof + "',className='" + u.className + "',tel='" + u.tel + "'  where stuNo=" + u.stuNo;
            if (DB.ExcuteCommand(sql))
            {
                Response.Write("<script type='text/javascript'>alert('修改成功!');window.location.href='/Admin/Stu';</script>");
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('添加失败!');window.location.href='/Admin/StuEdit?stuNo='"+u.stuNo+";</script>");
            }
            return View("StuAdd");
        }
        // 学生-删除
        [HttpGet]
        public EmptyResult StuDel(string stuNo)
        {
            string sql = "delete from stu where stuNo="+stuNo;
            if (DB.ExcuteCommand(sql))
            {
                Response.Write("<script type='text/javascript'>alert('删除成功!');window.location.href='/Admin/Stu';</script>");
            }
            else
            {
                Response.Write("<script type='text/javascript'>alert('删除失败!');window.location.href='/Admin/Stu';</script>");
            }
            return null;
        }
    }
}

 

 

包括源代码、数据库文档、数据库创建SQL脚本。一套基于ASP.NET MVC+EF6+Bootstrap开发出来的框架源代码! 采用主流框架,容易上手,简单易学,学习成本低。可完全实现二次开发、基本满足80%项目需求。 可以帮助解决.NET项目70%的重复工作,让开发更多关注业务逻辑。既能快速提高开发效率,帮助公司节省人力成本,同时又不失灵活性。 支持SQLServer、MySQL、Oracle、SQLite、Access 等多数据库类型。模块化设计,层次结构清晰。内置一系列企业信息管理的基础功能。 操作权限控制精密细致,对所有管理链接都进行权限验证,可控制到导航菜单、功能按钮。 数据权限(精细化数据权限控制,控制到行级,列表级,表单字段级,实现不同人看不同数据,不同人对同一个页面操作不同字段 兼容目前最流行浏览器(IE8+、Chrome、Firefox、360浏览器) 1、前端技术 JS框架:Bootstrap、JQuery CSS框架:Bootstrap v3.3.4(稳定是后台,UI方面根据需求自己升级改造吧)。 客户端验证:jQuery Validation Plugin。 在线编辑器:ckeditor、simditor 上传文件:Uploadify 数据表格:jqGrid、Bootstrap Talbe 对话框:layer 页面布局:jquery.layout.js 图表插件:echarts、highcharts 2、后端技术 核心框架:ASP.NET MVC5、WEB API 持久层框架:EntityFramework 定时计划任务:Quartz.Net组件 安全支持:过滤器、Sql注入、请求伪造 服务端验证:实体模型验证、自己封装Validator 缓存框架:微软自带Cache、Redis 日志管理:Log4net、登录日志、操作日志 工具类:NPOI、Newtonsoft.Json、验证码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌药ice

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值