jquery ajax与分页的实现(mvc下)
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery-1.2.6.min.js"></script>
<% if (false)
{ %>
<script type="text/javascript" src="http://www.cnblogs.com/Scripts/jquery-1.2.6-vsdoc.js"></script>
<%} %>
<script type="text/javascript">var jQuery = $;</script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery.formValidator.3.1.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery.formValidator.Regex.3.3.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery-plugins.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/lib/tg.protoaculous.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/lightwindow/lightwindow.js"></script>
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<div class="content_title_bgx content_loading" id="divContent">
<div id="PageContent">
</div>
<div id="Pagination" class="Pagination">
</div>
</div>
<div class="line">
</div>
<div class="fbzx">
发表咨询:
</div>
<div class="fbzx_main">
<p>
会 员:<%=Html.TextBox("txtUsrName1",IdentityUser.IsAuthenticated ? IdentityUser.UserName:"") %>
<label id="nickname">
</label>
密 码:<%=Html.Password("txtPassword", IdentityUser.IsAuthenticated ? IdentityUser.UserPassword : "")%>
<label id="password">
</label>
</p>
</div>
<p>
咨询内容:<textarea name="txtComment" id="txtComment" style="width: 426px; height: 130px;"></textarea>
<label id="message">
</label>
</p>
<div class="fl">
验
证 码:<input name="tbxVerifier" type="text" maxlength="5" id="tbxVerifier" style="width: 80px;" />
</div>
<div class="fl">
<a href="#none">
<img onclick="this.src=this.src+'?'" src="/Home/CommonVerifierCode" id="ivrVerifier"
height="23px" /></a><label id="verifier">
</label>
</div>
<div class="fbzx_btn">
<input name="iSave" type="button" onclick="validate('1');" id="iSave" value="提交" />
<input name="iCancle" type="button" id="iCancle" value="取消" />
</div>
<script type="text/javascript">
var orderby = ""; //进行排序的依据
var direction=1; //是否按顺序排序,0表顺序
jQuery(document).ready(function()
{
clearMessage();
InitData(0,1);
jQuery.formValidator.initConfig(
{
autotip: true
});
jQuery("#txtUsrName1")
.formValidator(
{
tipid: "nickname",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写用户名"
});
jQuery("#txtPassword")
.formValidator(
{
tipid: "password",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写密码"
});
jQuery("#txtComment")
.formValidator(
{
tipid: "message",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写信息"
});
jQuery("#tbxVerifier")
.formValidator(
{
tipid: "verifier",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 5,
onerror: "请填写验证码"
});
jQuery("#tbxVerifier").change(
function() {
jQuery("#tbxVerifier")
.ajaxValidator(
{
type: "GET",
url: "checkVerifierCode",
datatype: "json",
success:
function(result) {
if (result.Result == false)
document.getElementById('ivrVerifier').src += "?";
return result.Result;
},
buttons: jQuery("#iSave"),
onwait: "正在检测验证码...",
onerror: "验证码不正确"
});
});
jQuery("#iSave").click(
function()
{
if(validate('1')==true)
{
InitData(0,2);
}
}
);
jQuery("#iCancle").click(
function()
{
clearMessage();
}
);
});
function clearMessage()
{
jQuery("#txtComment").attr("value",'');
jQuery("#tbxVerifier").attr("value",'');
}
function validate(group)
{
return jQuery.formValidator.pageIsValid(group);
}
//这个事件是在翻页时候用的
function pageselectCallback(page_id, jq)
{
jQuery("#PageContent").empty();
jQuery("#Pagination").empty();
jQuery("#divContent").addClass("content_loading");
InitData(page_id,1);
}
function InitData(pageIndex,requestType)
{
var pageCount=0;//总记录数
var tbody = ""; //声明表格中body部分
var tempText="";
jQuery.ajax({
type: "POST",
dataType: "json",
url: '<%= ResolveUrl("~") %>PhotoComments/SaveComment', //请求的处理数据
data: "pageIndex=" + (pageIndex + 1) +"&requestType="+requestType+"&orderBy=" + orderby+ "&direction=" + direction+"&username="+jQuery("#txtUsrName1").val()+"&password="+jQuery("#txtPassword").val()+"&message="+jQuery("#txtComment").val()+"&verticode="+jQuery("#tbxVerifier").val(), //传入的参数,第一个参数就是分页的页数,第二个参数为排序的依据
error: function(){
tbody="数据加载失败";
jQuery("#PageContent").append(tbody);
},
//下面的操作就是成功返回数据以后,进行数据的绑定
success: function(data) {
var photoComments = data.PhotoCommentPageModels;
var error=data.Error;
pageCount=data.PageCount;
if(error=="")
{
for(var i=0;i<photoComments.length;i++)
{
tempText +='<tr ><td class="bl_1"'+'title='+photoComments[i].Comment+'>'+photoComments[i].Comment+'</td><td class="bl_2">'+photoComments[i].UserName+'</td><td>'+photoComments[i].CommentDate+'</td></tr>';
}
if(tempText!="")
tbody='<table>'+tempText+'</table>'
else
tbody="暂无评论";
jQuery("#PageContent").empty();
jQuery("#PageContent").append(tbody);
if(requestType=="2")
{
alert("提交成功!");
clearMessage();
}
//加入分页的绑定
jQuery("#Pagination").pagination(pageCount, {
callback: pageselectCallback,
prev_text: '< 上一页',
next_text: '下一页 >',
items_per_page: 5,
num_display_entries: 6,
current_page: pageIndex,
num_edge_entries: 2,
prev_show_always: false,
next_show_always: false
});
}
else
{
clearMessage();
alert(error);
}
},
complete: function(XMLHttpRequest, textStatus){
jQuery("#divContent").removeClass("content_loading");
}
});
}
</script>
后台所要用的代码
/// <summary>
/// 检测验证码输入是否正确
/// </summary>
/// <returns></returns>
public ActionResult checkVerifierCode()
{
string sCommentVerifier = Request["tbxVerifier"];
bool result = false;
if (!string.IsNullOrEmpty(sCommentVerifier))
result = sCommentVerifier.CompareTo(Session["TUKUCommonVerifierCode"]) != 0 ? false : true;
return Json(new { Result = result });
}
protected PhotoCommentPageData FillPhotoCommentPageData(int photoId, string sortFiled, bool direction, int pageIndex, int pageSize, out int recordCount)
{
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
IList<PhotoComment> photoComments = photoCommentRepository.GetPage(photoId, sortFiled, direction, pageIndex, pageSize, out recordCount);
IList<PhotoCommentPageModel> pageList = new List<PhotoCommentPageModel>();
PhotoCommentPageModel eTemp = null;
foreach (PhotoComment item in photoComments)
{
eTemp = new PhotoCommentPageModel();
eTemp.Comment = item.CommentContent;
eTemp.UserName = item.UserName;
eTemp.CommentDate = item.CommentDate.ToString();
pageList.Add(eTemp);
}
etPhotoCommentPageData.PhotoCommentPageModels = pageList;
etPhotoCommentPageData.PageCount = recordCount;
etPhotoCommentPageData.Error = "";
return etPhotoCommentPageData;
}
protected PhotoCommentPageData FillPhotoCommentPageData(string errMessage)
{
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
etPhotoCommentPageData.PhotoCommentPageModels = null;
etPhotoCommentPageData.PageCount = 10;
etPhotoCommentPageData.Error = errMessage;
return etPhotoCommentPageData;
}
public JsonResult SaveComment()
{
int pageIndex = 1;
bool isAsc = false;
int pageCount = 0;
string orderBy = Request["orderBy"];
string direction = Request["direction"];
int.TryParse(Request["pageIndex"], out pageIndex);
string photoId = "2";
string userId = string.Empty;
string message = Request["message"];
string requestType = Request["requestType"];
string userName = string.Empty;
string passWord = Request["password"];
string verifierCode = Request["verticode"];
string errrMessage = string.Empty;
if (string.IsNullOrEmpty(orderBy))
orderBy = "CommentDate";
if (direction == "0")
isAsc = true;
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
if (requestType == "1")
{
etPhotoCommentPageData = FillPhotoCommentPageData(int.Parse(photoId), orderBy, isAsc, pageIndex, 5, out pageCount);
}
else
{
if (verifierCode.CompareTo(Session["TUKUCommonVerifierCode"]) == 0)
{
userName = Request["username"];
UserInfo etUserInfo = userInfoRepository.Login(userName, passWord);
if (etUserInfo != null)
{
userId = etUserInfo.Id.ToString();
if (!photoCommentRepository.ReleaseComment(message, int.Parse(userId), int.Parse(photoId), userName))
{
errrMessage = "提交失败,数据插入失败!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
else
{
etPhotoCommentPageData = FillPhotoCommentPageData(int.Parse(photoId), orderBy, isAsc, pageIndex, 5, out pageCount);
}
}
else
{
errrMessage = "提交失败,用户名或密码错误!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
}
else
{
errrMessage = "提交失败,验证码错误!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
}
return Json(etPhotoCommentPageData);
}
<% if (false)
{ %>
<script type="text/javascript" src="http://www.cnblogs.com/Scripts/jquery-1.2.6-vsdoc.js"></script>
<%} %>
<script type="text/javascript">var jQuery = $;</script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery.formValidator.3.1.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery.formValidator.Regex.3.3.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/jquery-plugins.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/lib/tg.protoaculous.js"></script>
<script type="text/javascript" src="<%= ResolveUrl("~") %>Scripts/lightwindow/lightwindow.js"></script>
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<div class="content_title_bgx content_loading" id="divContent">
<div id="PageContent">
</div>
<div id="Pagination" class="Pagination">
</div>
</div>
<div class="line">
</div>
<div class="fbzx">
发表咨询:
</div>
<div class="fbzx_main">
<p>
会 员:<%=Html.TextBox("txtUsrName1",IdentityUser.IsAuthenticated ? IdentityUser.UserName:"") %>
<label id="nickname">
</label>
密 码:<%=Html.Password("txtPassword", IdentityUser.IsAuthenticated ? IdentityUser.UserPassword : "")%>
<label id="password">
</label>
</p>
</div>
<p>
咨询内容:<textarea name="txtComment" id="txtComment" style="width: 426px; height: 130px;"></textarea>
<label id="message">
</label>
</p>
<div class="fl">
验
证 码:<input name="tbxVerifier" type="text" maxlength="5" id="tbxVerifier" style="width: 80px;" />
</div>
<div class="fl">
<a href="#none">
<img onclick="this.src=this.src+'?'" src="/Home/CommonVerifierCode" id="ivrVerifier"
height="23px" /></a><label id="verifier">
</label>
</div>
<div class="fbzx_btn">
<input name="iSave" type="button" onclick="validate('1');" id="iSave" value="提交" />
<input name="iCancle" type="button" id="iCancle" value="取消" />
</div>
<script type="text/javascript">
var orderby = ""; //进行排序的依据
var direction=1; //是否按顺序排序,0表顺序
jQuery(document).ready(function()
{
clearMessage();
InitData(0,1);
jQuery.formValidator.initConfig(
{
autotip: true
});
jQuery("#txtUsrName1")
.formValidator(
{
tipid: "nickname",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写用户名"
});
jQuery("#txtPassword")
.formValidator(
{
tipid: "password",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写密码"
});
jQuery("#txtComment")
.formValidator(
{
tipid: "message",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 1,
onerror: "请填写信息"
});
jQuery("#tbxVerifier")
.formValidator(
{
tipid: "verifier",
onshow: "",
onfocus: "",
oncorrect: ""
})
.inputValidator(
{
min: 5,
onerror: "请填写验证码"
});
jQuery("#tbxVerifier").change(
function() {
jQuery("#tbxVerifier")
.ajaxValidator(
{
type: "GET",
url: "checkVerifierCode",
datatype: "json",
success:
function(result) {
if (result.Result == false)
document.getElementById('ivrVerifier').src += "?";
return result.Result;
},
buttons: jQuery("#iSave"),
onwait: "正在检测验证码...",
onerror: "验证码不正确"
});
});
jQuery("#iSave").click(
function()
{
if(validate('1')==true)
{
InitData(0,2);
}
}
);
jQuery("#iCancle").click(
function()
{
clearMessage();
}
);
});
function clearMessage()
{
jQuery("#txtComment").attr("value",'');
jQuery("#tbxVerifier").attr("value",'');
}
function validate(group)
{
return jQuery.formValidator.pageIsValid(group);
}
//这个事件是在翻页时候用的
function pageselectCallback(page_id, jq)
{
jQuery("#PageContent").empty();
jQuery("#Pagination").empty();
jQuery("#divContent").addClass("content_loading");
InitData(page_id,1);
}
function InitData(pageIndex,requestType)
{
var pageCount=0;//总记录数
var tbody = ""; //声明表格中body部分
var tempText="";
jQuery.ajax({
type: "POST",
dataType: "json",
url: '<%= ResolveUrl("~") %>PhotoComments/SaveComment', //请求的处理数据
data: "pageIndex=" + (pageIndex + 1) +"&requestType="+requestType+"&orderBy=" + orderby+ "&direction=" + direction+"&username="+jQuery("#txtUsrName1").val()+"&password="+jQuery("#txtPassword").val()+"&message="+jQuery("#txtComment").val()+"&verticode="+jQuery("#tbxVerifier").val(), //传入的参数,第一个参数就是分页的页数,第二个参数为排序的依据
error: function(){
tbody="数据加载失败";
jQuery("#PageContent").append(tbody);
},
//下面的操作就是成功返回数据以后,进行数据的绑定
success: function(data) {
var photoComments = data.PhotoCommentPageModels;
var error=data.Error;
pageCount=data.PageCount;
if(error=="")
{
for(var i=0;i<photoComments.length;i++)
{
tempText +='<tr ><td class="bl_1"'+'title='+photoComments[i].Comment+'>'+photoComments[i].Comment+'</td><td class="bl_2">'+photoComments[i].UserName+'</td><td>'+photoComments[i].CommentDate+'</td></tr>';
}
if(tempText!="")
tbody='<table>'+tempText+'</table>'
else
tbody="暂无评论";
jQuery("#PageContent").empty();
jQuery("#PageContent").append(tbody);
if(requestType=="2")
{
alert("提交成功!");
clearMessage();
}
//加入分页的绑定
jQuery("#Pagination").pagination(pageCount, {
callback: pageselectCallback,
prev_text: '< 上一页',
next_text: '下一页 >',
items_per_page: 5,
num_display_entries: 6,
current_page: pageIndex,
num_edge_entries: 2,
prev_show_always: false,
next_show_always: false
});
}
else
{
clearMessage();
alert(error);
}
},
complete: function(XMLHttpRequest, textStatus){
jQuery("#divContent").removeClass("content_loading");
}
});
}
</script>
后台所要用的代码
/// <summary>
/// 检测验证码输入是否正确
/// </summary>
/// <returns></returns>
public ActionResult checkVerifierCode()
{
string sCommentVerifier = Request["tbxVerifier"];
bool result = false;
if (!string.IsNullOrEmpty(sCommentVerifier))
result = sCommentVerifier.CompareTo(Session["TUKUCommonVerifierCode"]) != 0 ? false : true;
return Json(new { Result = result });
}
protected PhotoCommentPageData FillPhotoCommentPageData(int photoId, string sortFiled, bool direction, int pageIndex, int pageSize, out int recordCount)
{
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
IList<PhotoComment> photoComments = photoCommentRepository.GetPage(photoId, sortFiled, direction, pageIndex, pageSize, out recordCount);
IList<PhotoCommentPageModel> pageList = new List<PhotoCommentPageModel>();
PhotoCommentPageModel eTemp = null;
foreach (PhotoComment item in photoComments)
{
eTemp = new PhotoCommentPageModel();
eTemp.Comment = item.CommentContent;
eTemp.UserName = item.UserName;
eTemp.CommentDate = item.CommentDate.ToString();
pageList.Add(eTemp);
}
etPhotoCommentPageData.PhotoCommentPageModels = pageList;
etPhotoCommentPageData.PageCount = recordCount;
etPhotoCommentPageData.Error = "";
return etPhotoCommentPageData;
}
protected PhotoCommentPageData FillPhotoCommentPageData(string errMessage)
{
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
etPhotoCommentPageData.PhotoCommentPageModels = null;
etPhotoCommentPageData.PageCount = 10;
etPhotoCommentPageData.Error = errMessage;
return etPhotoCommentPageData;
}
public JsonResult SaveComment()
{
int pageIndex = 1;
bool isAsc = false;
int pageCount = 0;
string orderBy = Request["orderBy"];
string direction = Request["direction"];
int.TryParse(Request["pageIndex"], out pageIndex);
string photoId = "2";
string userId = string.Empty;
string message = Request["message"];
string requestType = Request["requestType"];
string userName = string.Empty;
string passWord = Request["password"];
string verifierCode = Request["verticode"];
string errrMessage = string.Empty;
if (string.IsNullOrEmpty(orderBy))
orderBy = "CommentDate";
if (direction == "0")
isAsc = true;
PhotoCommentPageData etPhotoCommentPageData = new PhotoCommentPageData();
if (requestType == "1")
{
etPhotoCommentPageData = FillPhotoCommentPageData(int.Parse(photoId), orderBy, isAsc, pageIndex, 5, out pageCount);
}
else
{
if (verifierCode.CompareTo(Session["TUKUCommonVerifierCode"]) == 0)
{
userName = Request["username"];
UserInfo etUserInfo = userInfoRepository.Login(userName, passWord);
if (etUserInfo != null)
{
userId = etUserInfo.Id.ToString();
if (!photoCommentRepository.ReleaseComment(message, int.Parse(userId), int.Parse(photoId), userName))
{
errrMessage = "提交失败,数据插入失败!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
else
{
etPhotoCommentPageData = FillPhotoCommentPageData(int.Parse(photoId), orderBy, isAsc, pageIndex, 5, out pageCount);
}
}
else
{
errrMessage = "提交失败,用户名或密码错误!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
}
else
{
errrMessage = "提交失败,验证码错误!";
etPhotoCommentPageData = FillPhotoCommentPageData(errrMessage);
}
}
return Json(etPhotoCommentPageData);
}