dhl:asp.net mvc下用jQuery ajax方法实现无刷新分页(用户控件)& 整体页面无刷新(2010-11-13 add)

2014.4.17 更新:

[OutputCache(Duration = 300)]
//condition是条件,page是当前页面
        public ActionResult Index(string condition = "", int page = 1)
        {
            if (condition.ToLower() != "all")
                condition = " category='" + Server.HtmlDecode(condition.Replace("'", "")) + "' ";
            else condition = "";
    //ToPagedList就是修改的MVCpager方法,参数:当前页号,分页大小,总记录数量
          //FindAllByPage是自己实现的分页方法,根据条件只取当前页面的数据
            PagedList<comnotices> notices = mgr.FindAllByPage(((page - 1) * 20).ToString(), "20", "", condition, 11).ToPagedList(page, 20, int.Parse(mgr.GetTotalCount("", condition)));
            if (Request.IsAjaxRequest())
                return PartialView("NewsAjaxList", notices);
            return View(notices);
        }

  

 


 

 

 

主页面:

 

代码
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage"%>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript" language="javascript">
$().ready(
function() {
$(
"#query_form").submit(function() {
jQuery.ajax(
{ data: jQuery.param(jQuery(
this).serializeArray()),
success:
function(request) { jQuery('#datalist').html(request); },
type:
'post',
url:
'../AdminForAgent/ManageSearch' });
returnfalse;
});
});
$().ready(
function() { $("#submit").submit(); });
</script>

<div class="search">
<fieldset>
<legend>设置查询条件(支持模糊查询)</legend>
<form action="<%=Url.Action("ManageSearch")%>" method="post" id="query_form">
<input type="hidden" name="page" id="page" value="1"/>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<th>代理商账号</th>
<td><input type="text" name="AgentId" id="AgentId"/></td>
<th>代理商名称</th>
<td><input type="text" name="AgentName" id="AgentName"/></td>
</tr>
<tr>
<th>代理商简称</th>
<td><input type="text" name="ShortAgentName" id="ShortAgentName"/></td>
<th>开户日期</th>
<td >
<input name="StartTime" type="text" id="StartTime" style="width:90px;" size="10" onclick="WdatePicker()"/>
<input name="EndTime" type="text" id="EndTime" style="width:90px;" size="10" onclick="WdatePicker()"/>
</td>
</tr>
<tr>
<th scope="row">销售员</th>
<td>
<input type="text" name="saleman" id="saleman"/>
</td>
<th>账户余额</th>
<td >
<input name="MinMoney" type="text" id="MinMoney" style="width:90px;" size="10"/>
<input name="MaxMoney" type="text" id="MaxMoney" style="width:90px;" size="10"" />
</td>
</tr>
<tr>
<td colspan="4"><input name="cc" id="submit" type="image" src="<%=Url.Content("~/Content/images/5.gif")%>" /></td>
</tr>
</table>
</form>
</fieldset>
</div>
<div id="datalist"></div>
</asp:Content>

 

 

用户控件页面:

 

代码
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<PagedList<KooCall.Dal.Agent>>"%>
<%@ Import Namespace="KooCall.Bll"%>
<%if (Model !=null&& Model.Count >0)
{
%>
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="tablelist">
<tr class="tabletitle">

<td>
代理商账号
</td>
<td>
代理商名称
</td>
<td>
代理商地区
</td>
<td>
联系人姓名
</td>
<td>
联系人电话
</td>
<td>
开户日期
</td>
<td>
余额
</td>
<td>
状态
</td>
<td>
编辑
</td>
</tr>
<%

foreach (KooCall.Dal.Agent agent in Model)
{
%>
<tr>
<td>
<%=agent.Id%>
</td>
<td>
<%--<%=Html.ActionLink(agent.FullCompanyName, "AgentAutoLogin", "Home", new { code = UserValidate.ValidateCodeCreate(agent.Id, Convert.ToInt32(ViewData["AdminId"])), toId = agent.Id, fromId = Convert.ToInt32(ViewData["AdminId"]), actor = ViewData["Actor"] }, new { target ="_blank" })%>--%>
<a href="http://agent.koocall.cc/home/AgentAutoLogin?code=<%=UserValidate.ValidateCodeCreate(agent.Id, Convert.ToInt32(ViewData["AdminId"])) %>&toId=<%=agent.Id %>&fromId=<%=Convert.ToInt32(ViewData["AdminId"]) %>&actor=<%=ViewData["Actor"] %>" target="_blank"><%=agent.FullCompanyName%></a>
</td>
<td>
<%=agent.Province%><%=agent.City%>
</td>
<td>
<%=agent.LinkName%>
</td>
<td>
<%=agent.LinkPhone%>
</td>
<td>
<%=agent.CreateTime.ToString("yyyy-MM-dd")%>
</td>
<td>
<%=agent.Balance /100%>.<%=agent.Balance % 100==0 ? "00" : (agent.Balance % 100).ToString()%>
</td>
<td>
<%=agent.Flag ? "正常" : "禁用"%>
</td>
<td>
<%=Html.ActionLink(agent.Flag ? "暂停" : "开通", "StopAgent", "AdminForAgent", new { agentId = agent.Id,page=Request["page"] }, new { target ="main" })%>|<%=Html.ActionLink("编辑", "Update", "AdminForAgent", new { agentId = agent.Id }, new { target ="main", title ="停用后代理商将不具备销售功能" })%>|
<%=Html.ActionLink("入账", "Charge", "AdminForAgent", new { agentId = agent.Id }, null)%>
<%--<a href="#" onclick="JqueryDialog.Open('入账', '<%=Url.Action("Charge", new { agentId = agent.Id })%>', 400, 300,true,true,true);">入账</a>--%>
<%=Html.ActionLink("入账明细", "ChargeLog", "AdminForAgent", new { agentId = agent.Id }, new { target ="main" })%>|
<%=Html.ActionLink("产品授权", "ProductLicenseList", "AdminForAgent", new { agentId = agent.Id }, new { target ="main" })%>|
<%=Html.ActionLink("重置密码", "ResetPassword", "AdminForAgent", new { agentId = agent.Id }, new { target ="main" })%>|
<%=Html.ActionLink("批量导入", "CustomerBatchCreate", "AdminForAgent", new { agentId = agent.Id }, new { target ="main" })%>
</td>
</tr>
<% }

%>
</table>
<div id="page_link" class="page"><%=KooCall.Utility.MvcPaging.GetNavigation(Model)%></div>
<%}
else
{
Response.Write(
"<div class='nothing'>暂无记录!</div>");
}
%>
<script type="text/javascript">
$(document).ready(
function() { $(".tablelist tr:even").addClass('trbj'); });
$(document).ready(
function() {
$(
"#page_link a").click(function() {
var cpage = $(this).text();
if (cpage =="上一页")
{ $(
"#page").val($("#page").val() -1); }
elseif (cpage =="下一页")
{ $(
"#page").val(parseInt($("#page").val()) +1); }
elseif (cpage =="末页")
{ $(
"#page").val(<%=Model.Count % ConfigFile.PerPageCount ==0? Model.Count / ConfigFile.PerPageCount : Model.Count / ConfigFile.PerPageCount+1%>); }
elseif (cpage =="首页")
{ $(
"#page").val(1); }
else {
$(
"#page").val(cpage);
}
$(
"#query_form").submit();
//$("#query_form").trigger("onsubmit");
returnfalse;
});
});
</script>

 

 

Controller:

public ActionResult Manage(int? page)
        {
            //var list = _agentManager.GetAgentList();
            //var pageList = new PagedList<Agent>(list, (page ?? 1), ConfigFile.PerPageCount);
            //ViewData["pcount"] = list.Count;
            //ViewData["AdminId"] = AdminId;
            //ViewData["Actor"] = Actor;
            //return View(pageList);//
            return View();
        }

        public ActionResult ManageSearch(int? page, FormCollection form)
        {
            DateTime startTime = DateTime.Now;
            DateTime endTime = DateTime.Now;
            var list = _agentManager.GetAgentList();
            if (!string.IsNullOrEmpty(form["AgentId"]))
            {
                int agentId = 0;
                int.TryParse(form["AgentId"].Trim(), out agentId);
                list = list.Where(p => p.Id == agentId).ToList();
            }

            if (!string.IsNullOrEmpty(form["AgentName"]))
            {
                list = list.Where(p => p.FullCompanyName.Contains(form["AgentName"].Trim())).ToList();
            }
            if (!string.IsNullOrEmpty(form["StartTime"]))
            {
                startTime = Convert.ToDateTime(form["StartTime"]);
                list = list.Where(p => p.CreateTime >= startTime).ToList();
            }

            if (!string.IsNullOrEmpty(form["EndTime"]))
            {
                endTime = Convert.ToDateTime(form["EndTime"]);
                //if (endTime == startTime)
                //    endTime = endTime.AddDays(1);
                endTime = endTime.AddDays(1);
                list = list.Where(p => p.CreateTime <= endTime).ToList();
            }
            if (!string.IsNullOrEmpty(form["ShortAgentName"]))
            {
                list = list.Where(p => p.ShortCompanyName.Contains(form["ShortAgentName"].Trim())).ToList();
            }
            if (!string.IsNullOrEmpty(form["SaleMan"]))
            {
                list = list.Where(p => p.SaleMan.Contains(form["SaleMan"].Trim())).ToList();
            }
            if (!string.IsNullOrEmpty(form["MinMoney"]))
            {
                int minMoney = 0;
                int.TryParse(form["MinMoney"], out minMoney);
                list = list.Where(p => p.Balance >= minMoney).ToList();
            }
            if (!string.IsNullOrEmpty(form["MaxMoney"]))
            {
                int maxMoney = 0;
                int.TryParse(form["MaxMoney"], out maxMoney);
                list = list.Where(p => p.Balance <= maxMoney).ToList();
            }
            var pageList = new PagedList<Agent>(list, page ?? 1, ConfigFile.PerPageCount);
            ViewData["pcount"] = list.Count;
            ViewData["AdminId"] = AdminId;
            ViewData["Actor"] = Actor;
            return PartialView("ManagePageList", pageList);
        }

 

重点:用jquery的ajax方法去服务器端取数据,然后把取出的数据显示到页面指定的分页数据处。

所以,用用户控件的return PartialView() 方法可以呈现部分视图到view. (即页面上没有<html><title><body><js>这样的标签的数据部分)。

但是这样还的建立一个部分视图的view页面,这时我想如果不建立数据视图页面,将整个当前页面再次载入一边是不是也可以?于是测试了一下,真的可以:

  可以整体页面无刷新的分页雏形(不正规,因为这样<html>这样的头标签又下载了一次,加载到页面上。):

 

<link href="/content/css/pagerclass.css" rel="stylesheet" type="text/css"/>
 <link href="/Content/Css/jj_find.css" rel="stylesheet" type="text/css"/>
               <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                //pager:
                $("div.pager  a").click(function () {
                    var tourl = $(this).attr("href");
                    //alert(tourl);
                    $.get(tourl,
                    function (data) {
                        $("body").empty().html(data);
                    }); //ajax end
                    return false;
                });
            });
    </script>
 
 <body>
<!--loop start-->
<%
PageList
<MyRequire> requireList = Model.RequireList;
if(requireList.List!=null&&requireList.List.Count>0)
{
foreach (
var require in requireList.List)
{
%>
<div class="JJF_Info">
<div class="Info_left">
<img src="/images/xq_tp.jpg"/>
</div>
<div class="Info_right">
<ul>
<li>
<div class="Info_BT">
<img src="/images/hotl.gif"/><span class="txt"><%=require.RequireTitle %></span>
</div>
<div class="Info_ll">
回复:
<span>2</span>个 浏览:40次&nbsp;&nbsp;<img class="ll_img" src="/images/bj_All_add.jpg" />
</div>
</li>
<li class="info_wz"><span class="txt_col">Leo提交</span>&nbsp;&nbsp;2010-8-29 07:59 </li>
<li class="info_wz">详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描述详细描</li>
<li class="info_wz">
<div class="wz_left">分类:语言&nbsp;&nbsp;&nbsp;&nbsp;标签:新概念 英语口语</div>
<div class="wz_right"><img src="/images/jj_an.jpg"/></div>
</li>
</ul>
</div>
</div>

<div class="JJ_dot">
</div>
<%
}
}
else
{
Html.NoDataString();
}
%>

<!--//loop-->

</div>
<div class="JJFind_right">
<div>
<img style="vertical-align:middle;" src="/images/hd_qz.gif"/>想分享你在各个领域的知识和经验么?想成为家教老师么?开心淘学让您跨越地域及空间的界限。
</div>
<div>
<img src="/images/sq.gif"/>
</div>
<div class="arr_info">
<img src="/images/arr2.gif"/><span class="arr_txt">了解一下教学平台</span>
</div>
<div class="arr_info">
<img src="/images/arr2.gif"/><span class="arr_txt2">如何成为一名老师</span>
</div>
<div class="arr_info">
<img src="/images/arr2.gif"/><span class="arr_txt2">免费体验</span>
</div>
<div class="right_txt">对家教老师或课程有特别需求?希望得到好的家教建议或帮助?</div>
<div class="right_xq">
<img src="/images/jj_xq.jpg"/>
</div>
</div>
</div>
<%=Html.PagerHtmlBuilder(requireList)%>
</div>
</body>

 

 

 

 OK,成功!做成htmlhelper类:

/// <summary>
        /// Ajax数字分页(基于jQuery1.4 请自己加载)2010-11-13
        /// </summary>
        /// <param name="helper">HtmlHelper</param>
        /// <param name="url">分页的URL(默认为本页)</param>
        /// <param name="pageList">IPagedList分页对象数据</param>
        /// <param name="pageLength">数字页码的长度</param>
        /// <returns></returns>
        public static string PagerHtmlBuilderForAjax(this HtmlHelper helper, string url, IPageList  pageList, int pageLength)
        {
            var sb = new StringBuilder();
            string str = PagerHtmlBuilder(helper, url, pageList, pageLength);
            sb.Append(str); //填充完毕

            sb.Append("<script language=\"javascript\" type=\"text/javascript\">");
            sb.Append("$(document).ready(function () {");
            sb.Append("$(\"div.pager  a\").click(function () {");
            sb.Append("var tourl = $(this).attr(\"href\");");
            sb.Append("$.get(tourl, function (data) {$(\"body\").empty().html(data);});");
            sb.Append("return false;");
            sb.Append("});");
            sb.Append("});");
            sb.Append("</script>");

            return sb.ToString();
        }

 

 

 附:

mvc 数字分页展示类

        /// <summary>
        /// 数字分页Paging with Numeric Pages 
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="url">分页的URL</param>
        /// <param name="pageList">IPagedList分页对象数据</param>
        /// <param name="pageLength">数字页码的长度</param>
        /// <returns></returns>
        public static string PagerHtmlBuilder(this HtmlHelper helper, string url, IPageList  pageList, int pageLength)
        {
            var sb = new StringBuilder();
            sb.Append("<div class=\"pager\">");
            sb.Append(string.Format("共{1}页/{0}条记录", pageList.TotalCount, pageList.TotalPages));
            string linkFormat = "";
            pageLength = (pageLength > pageList.TotalPages) ? pageList.TotalPages : pageLength;
            if (url.IndexOf('?') > 0) //有参数 (如:?sid=6、?sid=3&c=1、?page=1、?page=1&c=2、?t=3&page=2)
            {
                if (url.IndexOf("page=") > 0)  //有page参数
                {
                    //page参数后还有其他参数 (如:?page=2&type=2或?type=2&page=2&t=1)
                    if (url.Substring(url.IndexOf("page=")).IndexOf("&") > 0)  
                    {
                        var forward = url.Substring(0, url.IndexOf("page=")); //page前的部分
                        var endpar = url.Substring(url.LastIndexOf("page=") + 5); //page后的参数部分
                        url = forward + endpar.Substring(endpar.IndexOf("&") + 5);//去掉page后的部分
                        linkFormat = "<a href=\"{0}&page={1}\">{2}</a> ";
                    }
                    else //page参数后无其他参数 (如:?page=1、?type=2&page=2)
                    {
                        url = url.Remove(url.LastIndexOf("page="));
                        linkFormat = "<a href=\"{0}page={1}\">{2}</a> ";
                    }
                }
                else  //无page参数 (如:?type=2)
                {
                    linkFormat = "<a href=\"{0}&page={1}\">{2}</a> ";
                }
            }
            else //无参数
            {
                linkFormat = "<a href=\"{0}?page={1}\">{2}</a> ";
            }

            sb.Append(string.Format(linkFormat, url, "1", "首页"));//填充链接

            if (pageList.IsPreviousPage)
            {
                sb.Append(string.Format(linkFormat, url, (pageList.PageIndex - 1), "上一页"));
            }

            int cpage = Convert.ToInt32(HttpContext.Current.Request["page"] ?? "1");

            for (int j = 0, i = ((cpage - pageLength / 2 > 0) ? cpage - pageLength / 2 : 1); i <= pageList.TotalPages && j < pageLength; i++, j++)
            {
                if (i == cpage)
                {
                    sb.Append("<span class=\"current\">" + i + "</span>");
                }
                else
                {
                    sb.Append(string.Format(linkFormat, url, i, i));
                }
            }

            if (pageList.IsNextPage)
            {
                sb.Append(string.Format(linkFormat, url, (pageList.PageIndex + 1), "下一页"));
            }

            sb.Append(string.Format(linkFormat, url, pageList.TotalPages, "末页"));
            sb.Append("</div>");
            return sb.ToString();
        }

 

 

 

 

posted @ 2010-09-29 15:39  肚肚  阅读(1042)  评论(1编辑  收藏  举报