bootstrap table

bootstrap table 简单使用

  1. 创建mvc项目
  2. 添加控制器创建页面
  3. Good luck
    原文链接

初始化表格

<table id="tb1"></table>
@section Scripts{
<script src="~/Content/dist/bootstrap-table.js"></script>
<link href="~/Content/dist/bootstrap-table.css" rel="stylesheet" />
<script src="~/Content/dist/locale/bootstrap-table-zh-CN.js"></script>
    $(function () {
            $('#myModal').on('hide.bs.modal', function () {
                //表单的重置
                document.getElementById("form1").reset();
            })
            //表格方法
            ShowTable();
        })
 function ShowTable() {

            $('#tb1').bootstrapTable({
                url: '/Home/GetPageList',         //请求后台的URL(*)
                method: 'get',                      //请求方式(*)
               // toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
                pagination: true,                   //是否显示分页(*)
                sortable: false,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                //查询参数
                queryParams: function (queryParams) {
                    //name和collegeid是给后台的参数
                    queryParams.name = $("#txtStuName").val();
                    queryParams.collegeId = $("#ddl").val();
                    return queryParams;
                },//传递参数(*)
                sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
                pageNumber: 1,                       //初始化加载第一页,默认第一页
                pageSize: 10,                       //每页的记录行数(*)
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数(*)
                search: false,                       //是否显示表格搜索,此搜索是客户端搜索,不会进服务端,所以,个人感觉意义不大
                strictSearch: true,
                showColumns: false,                  //是否显示所有的列
                showRefresh: false,                  //是否显示刷新按钮
                minimumCountColumns: 2,             //最少允许的列数
                clickToSelect: true,                //是否启用点击选中行
                height: 500,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
                uniqueId: "id",                     //每一行的唯一标识,一般为主键列
                showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [{
                    checkbox: true
                }, {
                        field: 'name',
                        title: '名称'
                    }, {
                        field: 'sex',
                        title: '性别',
                        formatter: function (value, item, index) {
                            if (value == "1") {
                                return "男"
                            } else {
                                return "女"
                            }
                        }
                    }, {
                        field: 'phone',
                        title: '电话'
                    }, {
                        field: 'collegeName',
                        title: '学院'
                    }, {
                        field: 'admissionDate',
                        title: '入学时间',
                    formatter: function (value, item, index) {
                        return ChangeDateFormat(value)
                    }
                    }]
            });
        };

时间格式

function ChangeDateFormat(cellval) {
            var date = new Date(parseInt(cellval.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            return date.getFullYear() + "-" + month + "-" + currentDate ;
        }

触发事件按钮

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">添加</button>
<button class="btn btn-primary btn-lg" onclick="GetData()">修改</button>
<button class="btn btn-primary btn-lg" onclick="DelData()">删除</button>
姓名:<input id="txtStuName" /> 学院:<select id="ddl">
    <option value="">请选择</option>
    @foreach (var item in ViewBag.Colleges)
    {
        <option value="@item.id">@item.name</option>
    }
</select>
<input type="button" value="查询" onclick="QueryData()" />

模态框

<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    &times;
                </button>
            </div>
            <div class="modal-body">
                <form id="form1">
                    姓名:<input id="name" name="name" /> <br />
                    性别:<select id="sex" name="sex"><option value="1"></option><option value="0"></option></select> <br />
                    学院:<select id="collegeId" name="collegeId">
                        @foreach (var item in ViewBag.Colleges)
                        {
                            <option value="@item.id">@item.name</option>
                        }
                    </select> <br />
                    班级:<input id="class" name="class" /> <br />
                    职位:<input id="position" name="position" /> <br />
                    电话:<input id="phone" name="phone" /> <br />
                    入学时间:<input id="admissionDate" name="admissionDate" /> <br />
                    <input id="txtId" name="id" type="hidden" />
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    关闭
                </button>
                <button type="button" class="btn btn-primary" onclick="SaveData()">
                    提交更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->
</div>

查询

//查询(需要配置queryParams)
        function QueryData() {
            $("#tb1").bootstrapTable('refresh');
        }

删除

function DelData() {
            //获取选中行
            var checkedbox = $("#tb1").bootstrapTable('getSelections');

            if (checkedbox.length == 0) {
                alert("请选择要删除的数据");
                return;
            }

            var ids = [];
            for (var i = 0; i < checkedbox.length; i++) {
                ids.push(checkedbox[i].id);
            }

            if (confirm("是否删除数据")) {
                $.ajax({
                    url: "/Home/DelData",
                    data: {
                        ids: ids.toString()
                    }, success: function (res) {
                        if (res == "OK") {
                            alert("删除成功");
                            QueryData();
                        } else {
                            alert("删除失败")
                        }
                    }
                })
            }
        }

修改(回显)

//回显
        function GetData() {
            //获取选中行
            var checkedbox = $("#tb1").bootstrapTable('getSelections');
            if (checkedbox.length == 0) {
                alert("请选择要修改的数据");
                return;
            }

            if (checkedbox.length > 1) {
                alert("修改只能选一条");
                return;
            }

            $.ajax({
                url: "/Home/GetEditData",
                data: {
                    id: checkedbox[0].id
                },
                success: function (res) {
                    $('#myModal').modal('show');
                    $("#txtId").val(res.id);
                    $("#name").val(res.name);
                    $("#sex").val(res.sex);
                    $("#collegeId").val(res.collegeId);
                    $("#class").val(res.class);
                    $("#position").val(res.position);
                    $("#phone").val(res.phone);
                    $("#admissionDate").val(ChangeDateFormat(res.admissionDate));
                }
            })
        }

添加&修改

function SaveData() {
            var url = "";
            if ($("#txtId").val() == "") {
                url = "/Home/Add";
            } else {
                url = "/Home/Edit";
            }

            $.ajax({
                url: url,
                data: {
                    id:$("#txtId").val(),
                    name: $("#name").val(),
                    sex: $("#sex").val(),
                    collegeId: $("#collegeId").val(),
                    classId: $("#class").val(),
                    position: $("#position").val(),
                    phone: $("#phone").val(),
                    admissionDate: $("#admissionDate").val(),
                }, success: function (res) {
                    if (res == "OK") {
                        alert("操作成功");
                        //进行查询
                        QueryData();
                    } else {
                        alert("操作失败")
                    }
                    //关闭模态框
                    $('#myModal').modal('hide');
                }
            })
        }

后台代码

数据展示(分页&查询)

public ActionResult GetPageList(int limit,int offset,string name,string collegeId)
        {
            using (var db = new studbEntities())
            {
                var lst = (from a in db.Stus
                           join b in db.Colleges on a.collegeId equals b.id
                           select new StuDto
                           {
                               id = a.id,
                               name = a.name,
                               sex = a.sex,
                               phone = a.phone,
                               admissionDate = a.admissionDate,
                               position = a.position,
                               collegeId = a.collegeId,
                               collegeName = b.name,
                               @class = a.@class
                           });

                //查询条件拼接
                if (!String.IsNullOrWhiteSpace(name))
                {
                    lst = lst.Where(u => u.name.Contains(name));
                }
                if (!String.IsNullOrWhiteSpace(collegeId))
                {
                    int cid = int.Parse(collegeId);
                    lst = lst.Where(u => u.collegeId == cid);
                }

                int count = lst.Count();


                //分页,首先排序 -> Skip(offset) -> Take(limit)
                lst = lst.OrderBy(u => u.id).Skip(offset).Take(limit);


                return Json(new { total = count, rows = lst.ToList() }, JsonRequestBehavior.AllowGet);
            }
        }

删除

public ActionResult DelData(string ids)
        {
            using (var db = new studbEntities())
            {
                //1,2,3,4
                string[] lst = ids.Split(',');
                foreach (var item in lst)
                {
                    int id = int.Parse(item);
                    var model = db.Stus.Find(id);
                    //把查找出来的对象移除
                    db.Stus.Remove(model);
                }

                if (db.SaveChanges() > 0)
                {
                    return Content("OK");
                }
                else
                {
                    return Content("Error");
                }
            }
        }

添加

public ActionResult Add(string name,int sex,int collegeId,string classId,string position,string phone,string admissionDate)
        {
            using (var db = new studbEntities())
            {
                var model = new Stus();
                model.name = name;
                model.sex = sex;
                model.collegeId = collegeId;
                model.@class = classId;
                model.position = position;
                model.phone = phone;
                model.admissionDate = DateTime.Parse(admissionDate);
                model.createDate = DateTime.Now;//获取系统当前时间
                //把实体对象添加到数据库中
                db.Stus.Add(model);
                //做最终提交
                if (db.SaveChanges() > 0)
                {
                    return Content("OK");
                }
                else
                {
                    return Content("Error");
                }

            }
        }

修改

 public ActionResult Edit(int id,string name, int sex, int collegeId, string classId, string position, string phone, string admissionDate)
        {
            using (var db = new studbEntities())
            {
                var model = db.Stus.Find(id);
                model.name = name;
                model.sex = sex;
                model.collegeId = collegeId;
                model.@class = classId;
                model.position = position;
                model.phone = phone;
                model.admissionDate = DateTime.Parse(admissionDate);
     
               
                //做最终提交
                if (db.SaveChanges() > 0)
                {
                    return Content("OK");
                }
                else
                {
                    return Content("Error");
                }

            }
        }

最后登录

 public ActionResult UserLogin(string id,string pwd)
        {
            using (var db = new studbEntities())
            {
                var lst = db.Users.Where(u => u.id == id && u.pwd == pwd).ToList();
                if (lst.Count > 0)
                {
                    //跳转页面
                    //这里可以存sessoin然后在home页面进行判断session是否存在一个简单的拦截器就做好了
                    //Session["cookie"] = id;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return Content("<script>alert('用户名密码错误'); window.location.href='/Home/Login'</script>");
                }
            }
        }

祝好运

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值