C#EF 的Linq分页显示+Cookie存值取值
API代码:
//分页显示商品
[HttpGet]
public PageDate GetGoods(int index, int size)
{
PageDate page = new PageDate();
var list = db.Goods.ToList();
var count = list.Count();
page.List = list.OrderBy(x => x.GId).Skip((index - 1) * size).Take(size).ToList();
page.PageCount = count / size + (count % size == 0 ? 0 : 1);
return page;
}
//分页存储过程显示
[HttpGet]
public PageDate GetGoods2(int index, int size)
{
//实例化参数
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@index",index),
new SqlParameter("@size",size),
new SqlParameter("@totalcount",SqlDbType.Int), //总数据数
new SqlParameter("@pagecount",SqlDbType.Int), //总页数
};
//指定输出参数
parameters[2].Direction = ParameterDirection.Output;
parameters[3].Direction = ParameterDirection.Output;
//存储过程查询
var list = db.Database.SqlQuery<Goods>("exec sp_Show @index,@size,@totalcount out,@pagecount out", parameters).ToList();
PageDate page = new PageDate();
page.List = list;
page.PageCount = int.Parse(parameters[3].Value.ToString());
return page;
}
MVC代码:
<script>
var index1 = 0;
var pagecount = 0;
function load(index) {
index1 = index;
$.ajax({
url: "http://localhost:50825/api/Shopping/GetGoods2",
data: { index: index1, size: 2 },
type: "get",
dataType: "json",
success:
function (d) {
$("#tb").empty();
$(d.List).each(function () {
$("#tb").append(
'<tr>' +
'<td>' + this.Name + '</td>' +
'<td><img src="http://localhost:50825' + this.Img + '" width="80" height="60" /></td>' +
'<td>' + this.Price + '</td>' +
'<td><input id="Button1" type="button" value="加入购物车" onclick="addcar()" /></td>' +
'</tr>'
)
})
pagecount = d.PageCount;
}
})
}
load(1);
function first() {
index1 = 1;
load(index1);
}
function prve() {
index1--;
if (index1 == 0) {
index1 = 1;
}
load(index1);
}
function next() {
index1++;
if (index1 > pagecount) {
index1 = pagecount;
}
load(index1);
}
function last() {
load(pagecount);
}
//cookie零时存购物车
function addcar() {
//判断cookie是否有值
if (getCookie("shopcar") == null) {
//数组类型
setCookie("shopcar", "[]");
}
//这里举个例子,将值写死
var obj = {
Name: "球鞋",
Price: "1200"
};
//获取值,此时为字符串类型
var liststr = getCookie('shopcar');
//类型转换
var list = JSON.parse(liststr);
//追加值
list.push(obj);
//保存到cookie中
setCookie("shopcar", JSON.stringify(list));
location.href = "/Default/ShopCar";
}
//取值
function setCookie(name, value) {
if (value) {
var days = 1; //定义一天
var exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
// 写入Cookie, toGMTString将时间转换成字符串
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString;
}
};
//存值
function getCookie(name) {
var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); //匹配字段
if (arr = document.cookie.match(reg)) {
return unescape(arr[2]);
} else {
return null;
}
};
</script>

浙公网安备 33010602011771号