@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" type="text/css" href="~/Scripts/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="~/Scripts/themes/icon.css">
    @*<link rel="stylesheet" type="text/css" href="~/Scripts/demo.css">*@
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.easyui.min.js"></script>
    <script src="~/Scripts/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
        $(function () {

$('#dg').datagrid({
                url: '/Main/FenYe1',
                loadMsg: '请稍等,正在拼命加载...',
                fitColumns: false,//防止水平滚动
                rownumbers: true, //是否加行号
                pagination: true, //是否显式分页
                pageSize: 5, //页容量,必须和pageList对应起来,否则会报错
                pageNumber: 1, //默认显示第几页
                pageList: [5, 10, 15],//分页中下拉选项的数值
                checkOnSelect: true,
                selectOnCheck: true,

//固定列
                frozenColumns: [[
                    {
                        field: 'id', title: '请选择..', width: 58, align: 'center',
                        checkbox: true
                    },
                    { field: 'name', title: '名称', width: 100 },
                ]],
                //非固定列
                columns: [[ 
                    { field: 'sex', title: '性别', width: 100 },
                    { field: 'age', title: '年龄', width: 100 },
                    { field: 'dataTime', title: '记录时间', width: 150, align: 'center' },
                    { field: 'content', title: '个人介绍', width: 250, align: 'left' },

]],
                //导航栏('-')表示'|'分隔符
                toolbar: [
               { text: '增加', iconCls: 'icon-add', handler: function () { addStu(); } }, '-',
               { text: '修改', iconCls: 'icon-edit', handler: function () { edittbUser(); } }, '-',
               { text: '删除', iconCls: 'icon-remove', handler: function () { deleteUser(); } }, '-',
               { text: '查看', handler: function () { } }, '-',
               { text: '刷新', iconCls: 'icon-reload', handler: function () { deviceInfoRefreshClick(); } }, '-',
               { text: '导出', iconCls: 'icon-save', handler: function () { $(dg).treegrid('reload'); } }, '-'],
            });
        });

//添加
        function addStu() {
            $("#j_addStu").dialog({
                title: "新添学生1",
                width: 500,
                height: 450,
                href: '/Main/Add_View',
                buttons: [{
                    text: '新增',
                    handler: function () {
                        add();
                    }
                },{
                    text:'关闭',
                    handler: function () {
                        $('#j_addStu').dialog('close');
                    }
                }],

});
 
        }

function add() {

//是一个验证表单的功能。当validate()这个函数返回值是true的时候,表单提交,反之则不提交。

$("#addForm").form('submit', {
                url: '/Main/AddStu',
                onSubmit: function () {

return $(this).form('validate');
                },

success: function (data) {

if (data == 'ok') {
                        $.messager.show({
                            title: 'success',
                            msg: '插入成功!'
                        });
                        // $(dialogId).dialog('close');
                        $('#dg').datagrid('reload');
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: '插入失败!'
                        });
                    }

//$(dialogId).dialog('close');
                    $('#dg').datagrid('reload');
                }
            });
        }

//  删除代码部分
        function deleteUser() {
            var row = $('#dg').datagrid('getChecked');
            if (row) {
                //id字符串
                var idsStr = "";
                var arr = new Array();
                for (var i = 0; i < row.length; i++) {
                    //必须设置它为局部变量,否则会出现多条重复数据
                    var map = {};
                    map["id"] = row[i].id;
                    arr[i] = map;
                }
                for (var i = 0; i < arr.length; i++) {
                    idsStr += arr[i].id + ",";
                }
                if (idsStr.length > 0) {
                    idsStr = idsStr.substr(0, idsStr.length - 1);
                }
                $.messager.confirm('删除提示', '确定要删除吗', function (r) {
                    if (r) {
                        $.post('/Main/DelStu', { "idsStr": idsStr }, function (data, status) {

if (data == "ok") {
                                $.messager.show({
                                    title: 'success',
                                    msg: '删除成功!'
                                });
                                $('#dg').datagrid('reload');

} else {
                                $.messager.show({
                                    title: 'Error',
                                    msg: '删除用户失败!'
                                });
                            }
                        });
                    }
                });
            }
            else {
                //$.messager.show({
                //    title: 'Error',
                //    msg: '你没有选中行!'
                //});
                $.messager.alert("提示", "您没有选中任何行!");
            }
        }

//编辑
        function edittbUser() {
            $("#edittbStuDialog").dialog({
                title: "修改信息1",
                width: 500,
                height: 450,
                //href: '/Main/Update_View',
                buttons: [{
                    text: '修改',
                    handler: function () {
                        edit();
                    }
                }, {
                    text: '关闭',
                    handler: function () {
                        $('#edittbStuDialog').dialog('close');
                    }
                }],

});
            //getSelected返回第一个被选中的行或如果没有选中的行则返回null。
            var row = $('#dg').datagrid('getSelected');
            if (row) {

$("#editForm").form('load', {
                    name:row.name,
                    sex:row.sex,
                    age:row.age,
                    content:row.content
                });
                url = '/Main/UpdateStu?id=' + row.id;
            }
            else {
                $('#edittbStuDialog').dialog('close');
                $.messager.alert("提示", "您没有选中任何行!");
            }
        }

function edit() {

$("#editForm").form('submit', {
                url:url,
                onSubmit: function () {
                    // alert(formId);
                    return $(this).form('validate');

},

success: function (data) {

if (data == 'ok') {
                        $.messager.show({
                            title: 'success',
                            msg: '修改成功!'
                        });
                        $("#edittbStuDialog").dialog('close');
                        $('#dg').datagrid('reload');
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: '修改失败!'
                        });
                    }
                    //$(dialogId).dialog('close');
                    $('#ReceiveList').datagrid('reload');
                }
            });
        }

</script>
</head>
<body>
    <table id="dg" style="width:700px;height:800px;"></table>

@*data-options="required:true"自动验证:此输入项为必填项*@
    @*增加class="easyui-dialog"自定义弹出框*@
    <div id="j_addStu" style="padding:10px 20px"></div>

@*修改*@
    <div id="edittbStuDialog" style="padding:10px 20px; display:none">

<form id="editForm" method="post">
            <table class="align-center">
                <tr>
                    <td>学生名</td>
                    <td><input name="name" class="easyui-validatebox" type="text" /></td>
                </tr>
                <tr>
                    <td>性别</td>
                    <td><input name="sex" class="easyui-validatebox" type="text" /></td>
                </tr>
                <tr>
                    <td>年龄</td>
                    <td><input name="age" class="easyui-validatebox" type="text" /></td>
                </tr>
                <tr>
                    <td>个人介绍</td>
                    <td><textarea rows="5" class="easyui-validatebox" cols="19" name="content"></textarea></td>
                </tr>

</table>

</form>
    </div>

</body>
</html>

MainController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace DataGrid_01.Controllers
{
    public class MainController : Controller
    {
        DbContext db = new TestEntities();
        //DbContextFactory dbcontext = new DbContextFactory();
        //TestEntities db = dbcontext.GetDbContext();

#region 01-主页面
        /// <summary>
        /// 01-主页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        #endregion

#region 02-进行分页操作
        /// <summary>
        /// 02-分页
        /// </summary>
        /// <param name="rows">每页显示的记录数</param>
        /// <param name="page">页码,显示第几页</param>
        /// <returns></returns>
        public ActionResult FenYe1(int rows, int page)
        {
            try
            {
                var Stu_List = db.Set<student>().OrderByDescending(a => a.dataTime).Skip(rows * (page - 1)).Take(rows).ToList();
                var json = new
                {
                    total = db.Set<student>().Count(),
                    rows = (from r in Stu_List
                            select new
                            {
                                id = r.id,
                                name = r.name,
                                sex = r.sex,
                                age = r.age,
                                dataTime = r.dataTime.ToString(),
                                content = r.content,

}).ToList(),

};

return Json(json);
            }
            catch (Exception ex)
            {
                FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
                return Content("error");
            }
        }
        #endregion

#region 03-增加操作
        /// <summary>
        /// 03-增加操作
        /// </summary>
        /// <param name="name">学生姓名</param>
        /// <param name="sex">性别</param>
        /// <param name="age">年龄</param>
        /// <param name="content">个人介绍</param>
        /// <returns></returns>
        public ActionResult AddStu(string name, string sex, string age, string content)
        {
            try
            {
                student stu = new student()
                {
                    id = Guid.NewGuid().ToString("N"),
                    name = name,
                    sex = sex,
                    age = age,
                    content = content,
                    dataTime = DateTime.Now,

};
                db.Entry(stu).State = EntityState.Added;
                int count = db.SaveChanges();
                if (count > 0)
                {
                    return Content("ok");
                }
                else
                {
                    return Content("error");
                }
            }
            catch (Exception ex)
            {
                FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
                return Content("error");
            }

}
        #endregion

#region 04-删除
        /// <summary>
        /// 04-删除
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public ActionResult DelStu(string idsStr)
        {
            try
            {
                string[] str = idsStr.Split(new char[] { ',' });

//int[] str_int = Array.ConvertAll(str, int.Parse);

foreach (var item in str)
                {
                    var del = db.Set<student>().Where(a => a.id == item).FirstOrDefault();
                    db.Entry<student>(del).State = EntityState.Deleted;
                }
                int count = db.SaveChanges();
                if (count > 0)
                {
                    return Content("ok");
                }
                else
                {
                    return Content("error");
                }

}
            catch (Exception ex)
            {
                FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
                return Content("error");
            }
        }
        #endregion

#region 05-修改
        /// <summary>
        /// 05-修改
        /// </summary>
        /// <param name="id">id</param>
        /// <param name="name">学生名</param>
        /// <param name="sex">性别</param>
        /// <param name="age">年龄</param>
        /// <param name="content">个人介绍</param>
        /// <returns></returns>
        public ActionResult UpdateStu(string id, string name, string sex, string age, string content)
        {
            try
            {
                var stuList = db.Set<student>().Where(a => a.id == id).FirstOrDefault();
                stuList.name = name;
                stuList.sex = sex;
                stuList.age = age;
                stuList.dataTime = DateTime.Now;
                stuList.content = content;
                db.Entry(stuList).State = EntityState.Modified;
                int count = db.SaveChanges();
                if (count > 0)
                {
                    return Content("ok");
                }
                else
                {
                    return Content("error");
                }
            }
            catch (Exception ex)
            {
                FileOperateHelp.WriteFile("E:/ErrorLog333.txt", ex.Message);
                return Content("error");
            }
        }
        #endregion

#region 06-修改页面
        /// <summary>
        /// 06-修改页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Update_View()
        {
            return View();
        }
        #endregion

//增加页面
        public ActionResult Add_View() {
            return View();
        }
    }
}

.net+EF+mvc通过EasyUI的DataGrid实现增删改查的更多相关文章

  1. SSM框架搭建(Spring+SpringMVC+MyBatis)与easyui集成并实现增删改查实现

    一.用myEclipse初始化Web项目 新建一个web project: 二.创建包 controller        //控制类 service //服务接口 service.impl //服务 ...

  2. 【转载】ASP.NET MVC Web API 学习笔记---联系人增删改查

    本章节简单介绍一下使用ASP.NET MVC Web API 做增删改查.目前很多Http服务还是通过REST或者类似RESP的模型来进行数据操作的.下面我们通过创建一个简单的Web API来管理联系 ...

  3. ASP.NET MVC Web API 学习笔记---联系人增删改查

    本章节简单介绍一下使用ASP.NET MVC Web API 做增删改查. 目前很多Http服务还是通过REST或者类似RESP的模型来进行数据操作的. 下面我们通过创建一个简单的Web API来管理 ...

  4. EF(Entity Framework)通用DBHelper通用类,增删改查以及列表

    其中 通用类名:DBhelper 实体类:UserInfo 1 //新增 2 DBHelper<UserInfo> dbhelper = new DBHelper<UserInfo& ...

  5. asp.net EasyUI DataGrid 实现增删改查

    转自:http://www.cnblogs.com/create/p/3410314.html 前台代码: <!DOCTYPE html> <html xmlns="htt ...

  6. 3、ASP.NET MVC入门到精通——Entity Framework增删改查

    这里我接上讲Entity Framework入门.从网上下载Northwind数据库,新建一个控制台程序,然后重新添加一个ado.net实体数据模型. EF中操作数据库的"网关"( ...

  7. MVC ---- EF4.0和EF5.0增删改查的写法区别及执行Sql的方法

    EF4.0和EF5.0增删改查的写法区别 public T AddEntity(T entity) { //EF4.0的写法 添加实体 //db.CreateObjectSet<T>(). ...

  8. ASP.NET Identity系列02,在ASP.NET MVC中增删改查用户

    本篇体验在ASP.NET MVC中使用ASP.NET Identity增删改查用户. 源码在这里:https://github.com/darrenji/UseIdentityCRUDUserInMV ...

  9. EF Codefirst 多对多关系 操作中间表的 增删改查(CRUD)

    前言 此文章只是为了给新手程序员,和经验不多的程序员,在学习ef和lambada表达式的过程中可能遇到的问题. 本次使用订单表和员工表建立多对多关系. 首先是订单表: public class Ord ...

随机推荐

  1. Splay 区间反转

    同样的,我们以一道题来引入. 传送门 这次的任务比较少,只要求进行区间反转.区间反转? 这个好像用啥都是O(n)的吧……(这次vector,set也救不了你了) 我们来使用splay解决这个问题.我们 ...

  2. STM32F4 DMA2D_R2M

    图像处理的专门DMA 看一段示例代码 /** * @brief Displays a line. * @param Xpos: specifies the X position. * @param Y ...

  3. vs2008添加消息函数方法

    开发MFC时,开发工具VS2008不能像开发工具VC++6.0那样,直接在类文件上右击选择“Add Window Message Handles”来添加消息映射.对于我这个初学者,刚开始一直没找到可以 ...

  4. Gym 100512F Funny Game (博弈+数论)

    题意:给两个数 n,m,让你把它们分成 全是1,每次操作只能分成几份相等的,求哪一个分的次数最多. 析:很明显,每次都除以最小的约数是最优的. 代码如下: #pragma comment(linker ...

  5. UVa 12712 && UVaLive 6653 Pattern Locker (排列组合)

    题意:给定 一个n * n 的宫格,就是图案解锁,然后问你在区间 [l, r] 内的所有的个数进行组合,有多少种. 析:本来以为是数位DP,后来仔细一想是排列组合,因为怎么组合都行,不用考虑实际要考虑 ...

  6. mysql error:You can't specify target table for update in FROM clause

    mysql中You can't specify target table for update in FROM clause错误的意思是说,不能先select出同一表中的某些值,再update这个表( ...

  7. 小程序各种授权封装、saveImageToPhotosAlbum、chooseAddress、getUserInfo、getLocation,保存图片、获取用户信息、获取位置信息、收货地址等

    代码略多,请异步 github __点击链接

  8. jQuery笔记之Easing Plugin

    jQuery easing 使用方法首先,项目中如果需要使用特殊的动画效果,则需要在引入jQuery之后引入jquery.easing.1.3.js<script type="text ...

  9. postgreSQL 创建user表时引发的表名大写与双引号问题

    在postgreSQL里面,user是一个保留字. 如果你想创建user表,你可能会遭遇一些问题! 如图: 可以看到,这里是无法创建user表的. 你可能会说,我只是没有加双引号"" ...

  10. SpringMVC Model,ModelMap ModelAndView

    SpringMVC 调用方法之前会创一个隐含的模型对象(即Model,ModelMap ModelAndView) //@ModelAttribute 先于login方法执行 @ModelAttrib ...