一、创建DBFirst
1.首先创建一个文件夹
2.添加实体数据模型
3.选择来自数据库EF设计
4.选择新建链接
5.选择服务器
6.选择数据库
7.选择要在模型中对象
二、DAL层
//例子:
public List<UserInfo> show(out int totalcount, out int totalpage, string uname, int pageindex, int pagesize)
{
//执行存储过程
SqlParameter[] sqls =
{
new SqlParameter("@pageindex",pageindex),
new SqlParameter("@pagesize",pagesize),
new SqlParameter("@uname",uname==null?"":uname),
new SqlParameter("@totalcount",System.Data.SqlDbType.Int),
new SqlParameter("@totalpage",System.Data.SqlDbType.Int)
};
sqls[3].Direction = System.Data.ParameterDirection.Output;
sqls[4].Direction = System.Data.ParameterDirection.Output;
var list = db.Database.SqlQuery<UserInfo>("exec p_page @pageindex,@pagesize,@uname,@totalcount out,@totalpage out", sqls).ToList();
totalcount = (int)sqls[3].Value;
totalpage = (int)sqls[4].Value;
return list;
}
}
三、控制器
注意:ajax方法和视图是分开的
//例子:
//视图
public ActionResult Index()
{
return View();
}
//方法
[HttpGet]
public ActionResult show(string uname, int pageindex = 1, int pagesize = 3)
{
int totalcount;
int totalpage;
var list = dal.show(out totalcount, out totalpage, uname, pageindex, pagesize);
return Json(new { list, totalcount, totalpage }, JsonRequestBehavior.AllowGet);
}
四、视图
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<h2>Index</h2>
姓名:
<input type="text" id="uname" value="" />
<input type="button" class="btn btn-success" value="查询" onclick="show()" />
<table class="table table-bordered">
<thead>
<tr>
<td>账号</td>
<td>密码</td>
<td>是否删除</td>
<td>性别</td>
<td>邮箱</td>
<td>时间</td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
<a href="#" onclick="page('F')">首页</a>
<a href="#" onclick="page('P')">上一页</a>
<a href="#" onclick="page('N')">下一页</a>
<a href="#" onclick="page('L')">尾页</a>
<script>
var pageindex = 1;
var pagesize = 2
var totalcount;
var totalpage;
$(function () {
show();
})
function show() {
$.get('/Default/show', {
uname: $("#uname").val(),
pageindex: pageindex,
pagesize: pagesize
},
function (res) {
var str;
totalcount = res.totalcount;
totalpage = res.totalpage;
$("#tb").empty();
$.each(res.list, function () {
str += "<tr>"
+"<td>"+this.UName+"</td>"
+"<td>"+this.UPwd+"</td>"
+"<td>"+(this.UDell?"是":"否")+"</td>"
+"<td>"+(this.USex?"是":"否")+"</td>"
+"<td>"+this.UEim+"</td>"
+"<td>"+this.UTime+"</td>"
+"</tr>"
})
$("#tb").append(str);
})
}
function page(o) {
switch (o) {
case 'F': pageindex = 1; break;
case 'P': pageindex = pageindex <= 1 ? pageindex : pageindex - 1; break;
case 'N': pageindex = pageindex >= totalpage ? totalpage : pageindex + 1; break;
case 'L': pageindex = totalpage; break;
}
show();
}
</script>