学习篇:无刷新展示数据+分页+添加+修改+删除
首先说下用到的技术:EF+Jquery easyUI 没有用MVC3,先用的asp.net+.ashx 以后会做个MVC3的。
这里说的无刷新,就是通过jquery异步的方式,前后台来传数据。
1、首先,就是展示数据,这里我用了EF实体数据模型来生成EF对象,然后再对数据库的数据进行操作。
我这里用的是asp.net前台页面配合.ashx一般处理程序处理数据,来完成无刷新展示数据的效果。
展示数据,很容易的,用到jquery中的getJSON方法,将数据异步发送到一般处理程序处理,一般处理程序根据EF实体对象,获取数据库中的所有值。
将得到的数据,序列化成json格式的数据,返回到前台。
前台再拼接字符串,append()到指定的table表格中。展示数据,就大功告成了。
2、这里分页,用到了大牛写的一个分页的类,返回的是a标签,只要传入pageSize,currentPage,totalCount 就可以生产分页标签了。上面说到的取数据就不能一下全取出来,需要计算出这几个值,传入形成分页标签才成。
3、添加:这里用到了Jquery EasyUI插件,展示数据,弹出对话框都还比较的美观,而且用起来还算方便。 (dialog)
首先,想要添加用户,就需要一个表格来装用户信息,所以,我们就有了表格。
表格不能一开始就显示出来,需要我们点击“增加”按钮,才能够弹出来,所以,一开始就需要隐藏div;用到了$("#add_div").css("display", "none");来隐藏div
点击的时候显示出来就需要给按钮添加单击事件 $("#btnAddUser").click(function () {.......}。还要将隐藏的div展示出来$("#add_div").css("display", "block");
然后就是用到了easyui中的dialog()方法,展示出表格来。
接着就是填信息,取信息到后台,ef实体对象将其增加到数据库。
4、修改:稍微有点麻烦,但思想都是一样的。只是点击修改的时候,需要将当前要修改的内容先显示到表格中,这就需要传来id去到全部数据,所以写了一个GetModelById.ashx来取到这些数据。然后就是SaveChanges() 了 。
5、删除,链接传个id根据id来删除当前的数据,不过用的是异步,用的是remove()方法。关键找到要删除的tr标签。
具体代码如下:
前台 js+html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxShowList.aspx.cs" Inherits="Asp_EF_AJAX.Ajax.AjaxShowList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="../Styles/NavPager.css" rel="stylesheet" type="text/css" />
<link href="../Styles/tableStyle.css" rel="stylesheet" type="text/css" />
<link href="../Styles/themes/default/easyui.css" rel="stylesheet" type="text/css" />
<link href="../Styles/themes/icon.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.easyui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
//隐藏需要弹出的div
$("#add_div").css("display", "none");
$("#edit_userInfo").css("display", "none");
//初始化表格数据
initTableList("");
$("#btnAddUser").click(function () {
$("#add_div").css("display", "block");
$("#add_div").dialog({
title: "添加用户",
width: 600,
height: 400,
resizable: true
});
});
$("#add_user").click(function () {
var param = {
LoginId: $("#userName").val(),
LoginPwd: $("#password").val(),
Name: $("#realName").val(),
Address: $("#address").val(),
Phone: $("#phone").val(),
Mail: $("#mail").val(),
Money: $("#money").val()
};
$.post("/Ashx/AddUsers.ashx", param, function (data) {
if (data == "ok") {
$("#add_div").dialog("close");
initTableList("");
}
});
});
//单击修改表格上的修改按钮单击事件
$("#btnEditUserInfo").click(function () {
var id = $("#user_id").text();
var param = {
id: $("#user_id").text(),
LoginId: $("#edit_loginId").val(),
LoginPwd: $("#edit_loginPwd").val(),
Name: $("#edit_name").val(),
Address: $("#edit_address").val(),
Phone: $("#edit_phone").val(),
Mail: $("#edit_mail").val(),
Money: $("#edit_money").val(),
};
$.post("/Ashx/EditUserInfo.ashx", param, function (data) {
if(data=="ok"){
$("#edit_userInfo").dialog("close");
initTableList("");
}
});
});
});
//绑定表格数据列表
function initTableList(param) {
$.getJSON("/Ashx/LoadAllUsers.ashx", param, function (data) {
if (data.Rows.length > 0) {
//清理之前的标签,防止重复加载
$(".dataTr").remove();
$("#pageNav").html("");
//处理表格数据
var strTrs = "";
for (var i = 0; i < data.Rows.length; i++) {
var user = data.Rows[i];
var strTr = "<tr class='dataTr'>";
strTr += "<td>" + user.Id + "</td>";
strTr += "<td>" + user.LoginId + "</td>";
strTr += "<td>" + user.LoginPwd + "</td>";
strTr += "<td>" + user.Name + "</td>";
strTr += "<td>" + user.Address + "</td>";
strTr += "<td>" + user.Phone + "</td>";
strTr += "<td>" + user.Mail + "</td>";
strTr += "<td>" + user.UserRoleId + "</td>";
strTr += "<td>" + user.UserStateId + "</td>";
strTr += "<td>" + user.Money + "</td>";
strTr += "<td><a href='javascript:void(0)' id="+user.Id+" class='deleteLink'>删除</a> <a href='javascript:void(0)' id=" + user.Id + " class='editLink'>修改</a></td>";
strTr += "</tr>";
strTrs += strTr;
}
$("#userList").append(strTrs);
}
//处理导航标签
$("#pageNav").append(data.Nav);
//再添加导航标签之后,绑定单击事件
bindNavLinkClick();
//等待修改增加上class后,再绑定单击事件
bindEditLinkClick();
//绑定删除单击事件
bindDeleteLinkClick();
});
}
//绑定删除的单击事件
function bindDeleteLinkClick(){
$(".deleteLink").click(function(){
// 这里注意了,如果如果要加上“提示信息” 注意$(this)应写在最上面了。
var userId=$(this).attr("id");
// alert(userId);
var current=$(this);
$.messager.confirm("提示信息~!","确认要删除吗~?",function (isOk) {
if (!isOk) {
alert("123");
return;
}
// alert(userId);
$.post("/Ashx/DeleteUserById.ashx",{id:userId},function(data){
if(data=="ok"){
// alert(current);
current.parent().parent().fadeOut();
}
});
})
return false;
});
}
//绑定修改链接的单击事件
function bindEditLinkClick() {
$(".editLink").click(function () {
var userId = $(this).attr("id");
$("#edit_userInfo").css("display", "block");
$("#edit_userInfo").dialog({
title: "添加用户",
width: 600,
height: 400,
resizable: true
});
$("#user_id").text(userId);
$.getJSON("/Ashx/GetModelById.ashx", { id: userId }, function (data) {
$("#edit_loginId").val(data.LoginId);
$("#edit_loginPwd").val(data.LoginPwd);
$("#edit_name").val(data.Name);
$("#edit_address").val(data.Address);
$("#edit_phone").val(data.Phone);
$("#edit_mail").val(data.Mail);
$("#edit_money").val(data.Money);
});
return false;
});
}
//绑定分页页码的单击事件
function bindNavLinkClick() {
$(".pageLink").click(function () {
var nav_href = $(this).attr("href");
var param = nav_href.substring(nav_href.indexOf('?') + 1, nav_href.length);
initTableList(param);
return false;
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<%--添加按钮--%>
<input type="button" name="txtAdd" value="添加用户" id="btnAddUser" />
<table id="userList" border="0" cellpadding="0" cellspacing="0">
<tr>
<%--Id, LoginId, LoginPwd, Name, Address, Phone, Mail, UserRoleId, UserStateId, Money--%>
<th>Id</th><th>LoginId</th><th>LoginPwd</th><th>Name</th><th>Address</th><th>Phone</th><th>Mail</th><th>UserRoleId</th><th>UserStateId</th><th>Money</th><th>操作</th>
</tr>
</table>
<div id="pageNav" class="paginator">
</div>
<%--增加的div--%>
<div id="add_div">
<table >
<tr>
<td>LoginId</td><td><input type="text" name="txtUserName" id="userName" /></td>
</tr>
<tr>
<td>LoginPwd</td><td><input type="text" name="txtPwd" id="password" /></td>
</tr>
<tr>
<td>Name</td><td><input type="text" name="txtName" id="realName" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="txtAddress" id="address" /></td>
</tr>
<tr>
<td>Phone</td><td><input type="text" name="txtPhone" id="phone" /></td>
</tr>
<tr>
<td>Mail</td><td><input type="text" name="txtMail" id="mail" /></td>
</tr>
<tr>
<td>Money</td><td><input type="text" name="txtMoney" id="money" /></td>
</tr>
</table>
<input type="button" name="btnAddUser" value="添加" id="add_user" />
</div>
<%--修改的div--%>
<div id="edit_userInfo">
<table >
<tr><td>ID</td><td><span id="user_id"></span></td></tr>
<tr>
<td>LoginId</td><td><input type="text" name="txtUserName" id="edit_loginId" /></td>
</tr>
<tr>
<td>LoginPwd</td><td><input type="text" name="txtPwd" id="edit_loginPwd" /></td>
</tr>
<tr>
<td>Name</td><td><input type="text" name="txtName" id="edit_name" /></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="txtAddress" id="edit_address" /></td>
</tr>
<tr>
<td>Phone</td><td><input type="text" name="txtPhone" id="edit_phone" /></td>
</tr>
<tr>
<td>Mail</td><td><input type="text" name="txtMail" id="edit_mail" /></td>
</tr>
<tr>
<td>Money</td><td><input type="text" name="txtMoney" id="edit_money" /></td>
</tr>
</table>
<input type="button" name="btnEdit" value="修改" id="btnEditUserInfo" />
</div>
</form>
</body>
</html>
LoadAllUsers.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using WebApplication1; namespace Asp_EF_AJAX.Ashx { /// <summary> /// LoadAllUsers 的摘要说明 /// </summary> public class LoadAllUsers : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; bookshopEntities dbContext = new bookshopEntities(); // var userList = dbContext.Users.ToList(); //把当前的标签取出来 int pageIndex=context.Request.QueryString["pageIndex"]==null?1:int.Parse(context.Request.QueryString["pageIndex"]); //总条数 int totalCount=dbContext.Users.Count(); string strNav = WebApplication1.Common.PageNav.ShowPageNavigate(10, pageIndex, totalCount); //当前页的数据 var pageData = dbContext.Users.OrderBy<Users, int>(b => b.Id).Skip<Users>((pageIndex - 1) * 10).Take<Users>(10); //封装数据到前台, 匿名类 var data = new {Nav=strNav,Rows=pageData }; System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //string strJson = javaScriptSerializer.Serialize(userList); string strJson = javaScriptSerializer.Serialize(data); context.Response.Write(strJson); } public bool IsReusable { get { return false; } } } }
AddUsers.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Ashx { /// <summary> /// AddUsers 的摘要说明 /// </summary> public class AddUsers : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); string userName = context.Request.Form["LoginId"]; string password = context.Request.Form["LoginPwd"]; string realName = context.Request.Form["Name"]; string address = context.Request.Form["Address"]; string phone = context.Request.Form["Phone"]; string mail = context.Request.Form["Mail"]; decimal money = decimal.Parse(context.Request.Form["Money"]); Users model = new Users(); model.LoginId = userName; model.LoginPwd = password; model.Name = realName; model.Address = address; model.Phone = phone; model.Mail = mail; model.UserRoleId = 1; model.UserStateId = 1; model.Money = money; bookshopEntities dbContext = new bookshopEntities(); dbContext.Users.AddObject(model); dbContext.SaveChanges(); context.Response.Write("ok"); } public bool IsReusable { get { return false; } } } }
GetModelById.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Ashx { /// <summary> /// GetModelById 的摘要说明 /// </summary> public class GetModelById : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); int id = context.Request.QueryString["id"] == null ? 0 : int.Parse(context.Request.QueryString["id"]); bookshopEntities dbContext = new bookshopEntities(); var user = dbContext.Users.Where<Users>(u => u.Id == id).FirstOrDefault(); System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string strJson = javaScriptSerializer.Serialize(user); context.Response.Write(strJson); } public bool IsReusable { get { return false; } } } }
EditUserInfo.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Ashx { /// <summary> /// GetModelById 的摘要说明 /// </summary> public class GetModelById : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); int id = context.Request.QueryString["id"] == null ? 0 : int.Parse(context.Request.QueryString["id"]); bookshopEntities dbContext = new bookshopEntities(); var user = dbContext.Users.Where<Users>(u => u.Id == id).FirstOrDefault(); System.Web.Script.Serialization.JavaScriptSerializer javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); string strJson = javaScriptSerializer.Serialize(user); context.Response.Write(strJson); } public bool IsReusable { get { return false; } } } }
DeleteUserById.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Ashx { /// <summary> /// DeleteUserById 的摘要说明 /// </summary> public class DeleteUserById : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //context.Response.Write("Hello World"); int id = context.Request.Form["id"] == null ? 0 : int.Parse(context.Request.Form["id"]); bookshopEntities dbContext = new bookshopEntities(); Users user = dbContext.Users.Where<Users>(u => u.Id == id).FirstOrDefault(); dbContext.DeleteObject(user); dbContext.SaveChanges(); context.Response.Write("ok"); } public bool IsReusable { get { return false; } } } }
PageNav.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; namespace WebApplication1.Common { public class PageNav { public static string ShowPageNavigate(int pageSize, int currentPage, int totalCount) { string redirectTo = ""; pageSize = pageSize == 0 ? 3 : pageSize; var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数 var output = new StringBuilder(); if (totalPages > 1) { if (currentPage != 1) {//处理首页连接 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize); } if (currentPage > 1) {//处理上一页的连接 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize); } else { // output.Append("<span class='pageLink'>上一页</span>"); } output.Append(" "); int currint = 5; for (int i = 0; i <= 10; i++) {//一共最多显示10个页码,前面5个,后面5个 if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages) { if (currint == i) {//当前页处理 //output.Append(string.Format("[{0}]", currentPage)); output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage); } else {//一般页处理 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint); } } output.Append(" "); } if (currentPage < totalPages) {//处理下一页的链接 output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize); } else { //output.Append("<span class='pageLink'>下一页</span>"); } output.Append(" "); if (currentPage != totalPages) { output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize); } output.Append(" "); } output.AppendFormat("第{0}页 / 共{1}页", currentPage, totalPages);//这个统计加不加都行 return output.ToString(); } } }
OK了。。。。呵呵,我上面说的那些,可以不用看了,代码倒是可以看看的,我有注视的哦....


浙公网安备 33010602011771号