标签:
Asp.Net Mvc+MongoDB简单增删查改
概要:现在很多企业都在使用非关系型的NoSql数据库,其中MongoDB是相当热门的,最近有空就研究了一下,本文写了一套基于Asp.Net Mvc和MongoDB的简单增删查改,本文部分内容是借用其他博文,最后我会贴出出处.
正文:
在控制器的Models中新建一个UserModel模型(其中相当于另开一个类库,类似Dal层)
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MvcApplication1.Models.Home { using Model; using MongoDB; public class UserModel { //链接字符串(此处三个字段值根据需要可为读配置文件) public string connectionString = "Server=127.0.0.1:27017"; //数据库名 public string databaseName = "DataBase_YZR"; //集合名 public string collectionName = "UserInfo"; private Mongo mongo; private MongoDatabase mongoDatabase; private MongoCollection<Document> mongoCollection; public UserModel() { mongo = new Mongo(connectionString); mongoDatabase = mongo.GetDatabase(databaseName) as MongoDatabase; mongoCollection = mongoDatabase.GetCollection<Document>(collectionName) as MongoCollection<Document>; mongo.Connect(); } ~UserModel() { mongo.Disconnect(); } /// <summary> /// 增加一条用户记录 /// </summary> /// <param name="doc"></param> public void Add(Document doc) { mongoCollection.Insert(doc); } /// <summary> /// 删除一条用户记录 /// </summary> public void Delete(string Name) { mongoCollection.Remove(new Document { { "Name", Name } }); } /// <summary> /// 更新一条用户记录 /// </summary> /// <param name="doc"></param> public void Update(Document doc) { mongoCollection.FindAndModify(doc, new Document { { "Name", doc["Name"].ToString() } }); } /// <summary> /// 查找所有用户记录 /// </summary> /// <returns></returns> public IEnumerable<Document> FindAll() { return mongoCollection.Find(c=>true).Documents; } } }
这里封装了一些的基本的增删查改操作,以及连接,数据库对象的创建等.
Note:详细看过的你会发现,UserInfo是基于Name作为主键,这里只是作为演示demo,具体业务需要具体做一些改变.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class UserInfo { private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } } }
控制器内容:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcApplication1.Controllers { using MongoDB; using MvcApplication1.Models.Home; using Model; using System.Text;
public class IndexController : Controller { // // BY YZR UserModel userModel = new UserModel(); public ActionResult Index() { return View(); } /// <summary> /// 获取全部用户列表,通过json将数据提供给jqGrid /// </summary> public JsonResult UserList() { string rows=Request["rows"]; string page=Request["page"]; var list = userModel.FindAll(); int i = 0; var query = from u in list select new { id = i++, Name=u["Name"].ToString(), Age=u["Age"].ToString() }; var data = new { total = query.Count() / Convert.ToInt32(rows) + 1, page = Convert.ToInt32(page), records = query.Count(), rows = query.Skip(Convert.ToInt32(rows) * (Convert.ToInt32(page) - 1)).Take(Convert.ToInt32(rows)) }; return Json(data, JsonRequestBehavior.AllowGet); } /// <summary> /// 响应Js的“Add”ajax请求,执行添加用户操作 /// </summary> public ActionResult Add() { StringBuilder sb = new StringBuilder(); string paramsdata=Request["data"]; string[] ss=paramsdata.Split(‘&‘); string name = ss[0]; name=name.Split(‘=‘)[1]; string age = ss[1]; age = age.Split(‘=‘)[1]; Document doc = new Document(); doc["Name"] = name; doc["Age"] = age; try { userModel.Add(doc); return Content("添加成功"); } catch { return Content("添加失败"); } } /// <summary> /// 响应Js的“Update”ajax请求,执行更新用户操作 /// </summary> public ContentResult Update() { //修改年龄 StringBuilder sb = new StringBuilder(); string paramsdata = Request["data"]; string[] ss = paramsdata.Split(‘&‘); string name = ss[0]; name = name.Split(‘=‘)[1]; string age = ss[1]; age = age.Split(‘=‘)[1]; Document doc = new Document(); doc["Name"] = name; doc["Age"] = age; try { userModel.Update(doc); return Content("修改成功"); } catch { return Content("修改失败"); } } /// <summary> /// 响应Js的“Delete”ajax请求,执行删除用户操作 /// </summary> public ContentResult Delete() { string name=Request["id"]; string[] names=name.Split(‘,‘); for (int i = 0; i < names.Length; i++) { try { userModel.Delete(names[i]); } catch { return Content("删除失败"); } } return Content("删除成功"); } } }
Index页面:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <link href="~/jquery-easyui-1.4.1/themes/default/easyui.css" rel="stylesheet" /> <link href="~/jquery-easyui-1.4.1/themes/icon.css" rel="stylesheet" /> <script src="~/jquery-easyui-1.4.1/jquery.min.js"></script> <script src="~/jquery-easyui-1.4.1/jquery.easyui.min.js"></script> <script src="~/js/myJs.js"></script> <script type="text/javascript"> $(function () { $("#tab").datagrid({ width: 1000, //宽度 height: 600, //高度 singleSelect: true, //选中一行的设置 rownumbers: true, //行号 url: "/Index/UserList", //请求路径 title: "EMP员工信息", //标题 iconCls: "icon-save", //图标 collapsible: true, //隐藏按钮 //列 columns: [[ { field: "id", title: "id", width: 80 }, { field: "Name", title: "name", width: 100 }, { field: "Age", title: "age", width: 100 } ]], //传输参数 queryParams: { "action": "query" }, pagination: true,//指示分页导航 toolbar: "#tool" }); $("#tab").datagrid(‘getPager‘).pagination({ beforePageText: "第", afterPageText: "页", displayMsg: "当前 {from} - {to}条数据 共{total} 条数据", pageSize: 1, pageList: [1,5, 10, 15, 20, 30] }); }) </script> </head> <body> <div> <table id="tab"> </table> <div id="tool"> <table border="0" cellspacing="0" cellpadding="0" width="100%"> <tr> <td style=" padding-left:2px"> <a href="#" class="easyui-linkbutton" id="id_add" iconcls="icon-add" plain="true" onclick="add_dg();" >添加</a> <a href="#" class="easyui-linkbutton" id="id_edit" iconCls="icon-edit" plain="true" onclick="edit_dg();">修改</a> <a href="#" class="easyui-linkbutton" id="id_cancel " onclick="delete_dg();" iconcls="icon-cancel" plain="true">删除</a> </td> </tr> </table> </div> <div id="dd_dg" style=" display:none"> <form id="fm_dg"> NAME:<input type="text" id="Name" name="Name" class="easyui-validatebox" required="true" missingMessage="请输入NAME" /> <br /> AGE:<input type="text" id="Age" name="Age" class="easyui-validatebox" required="true" missingMessage="请输入AGE" /> <br /> <input type="hidden" id="id" name="id"/> </form> </div> </div> </body> </html>
JS代码:
//by YZR
// easyui datagrid dateFormatter function formatterdate(val, row) { if (val != null) { var date = new Date(val); return date.getFullYear() + ‘-‘ + (date.getMonth() + 1) + ‘-‘ + date.getDate(); } } function delete_dg() { var selected = $("#tab").datagrid(‘getSelected‘); if (selected != null) { $.messager.confirm(‘提示‘, ‘是否确定要删除?‘, function (yes) { if (yes) { var ids = ""; var checked = $("#tab").datagrid(‘getChecked‘); $.each(checked, function (i, row) { ids += row.Name + ","; }) ids = ids.substring(0, ids.length - 1); $.post("/Index/Delete", { "action": "del", id: ids }, function (data) { $.messager.alert(‘提示‘, data); $("#tab").datagrid(‘reload‘); }); } }) } else { $.messager.alert(‘提示‘, ‘您还没有选中一行数,请选中在删除!‘); } } function add_dg() { //表单清空 $("#fm_dg")[0].reset(); //显示 $("#dd_dg").show(); //以窗体的形式展示 $("#dd_dg").dialog({ title: "添加EMP信息",//标题 iconCls: "icon-add",//图标 width: 600,//窗体的宽度 height: 400,//窗体的高度 modal: true, //遮罩层 //按钮集合 buttons: [ { text: "添加",//添加按钮的文本值 iconCls: "icon-ok", //添加按钮的图标 handler: function () { //将数据序列化 var parm = $("#fm_dg").serialize(); //中文格式转换 var pp = decodeURIComponent(parm, true); //post异步提交 $.post("/Index/Add", { "action": "add", data: pp }, function (data) { $.messager.alert(‘提示‘, data); //重新加载datagrid $("#tab").datagrid(‘reload‘); //关闭 $("#dd_dg").window(‘close‘); }); } }, { text: "取消", iconCls: "icon-cancel", handler: function () { $("#dd_dg").window("close"); } } ] }); } function edit_dg() { //选中一行,获取这一行的属性的值 var selected = $("#tab").datagrid(‘getSelected‘); //判断是否选中 if (selected != null) { //$("#id").val(selected.JSON_id); $("#id").val(selected.id); $("#Name").val(selected.Name); $("#Age").val(selected.Age); //取值显示性别 //if (selected.JSON_sex == "男") { // $("#sex option").eq(0).attr("selected", "selected"); //} else { // $("#sex option").eq(1).attr("selected", "selected"); //} $("#dd_dg").show(); //显示修改窗体 $("#dd_dg").dialog({ title: "编辑信息", iconCls: "icon-edit", modal: true,//遮罩层 width: 600, height: 400, buttons: [ { text: "编辑", iconCls: "icon-edit", handler: function () { var parm = $("#fm_dg").serialize(); var pp = decodeURIComponent(parm, true); $.post("/Index/Update", { "action": "edit", data: pp }, function (data) { $.messager.show({ title: "提示", msg: data }); $("#tab").datagrid("reload"); $("#dd_dg").window("close"); }); } }, { text: "取消", iconCls: "icon-cancel", handler: function () { $("#dd_dg").window(‘close‘); } } ] }); } else { $.messager.alert(‘提示‘, ‘请选中一行在进行编辑‘); } }
本文是参考的博文地址是:http://www.cnblogs.com/lipan/archive/2011/03/11/1980227.html
本文只用学习:
END
标签:
原文地址:http://www.cnblogs.com/Francis-YZR/p/4806767.html