MVC4中ajax分页技术实例

前端之家收集整理的这篇文章主要介绍了MVC4中ajax分页技术实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在这之前一直没有写过碰过MVC,更别说ajax,但是项目需要,只好边学边做了,希望跟我一样的朋友也可以看到文章,希望可以应用的到你们的项目中去。好了废话不多说,现在开始动手吧。

前台页面 Index.cshtml,这个页面主要是布局控件 引用样式和js

@{
    //收费查询页面   
    ViewBag.Title = "互联网云停车场-收费查询";
    @Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
    @Scripts.Render("~/Scripts/class.js")
    @Scripts.Render("~/Scripts/Validate.js")
    @Scripts.Render("~/Scripts/main/Select.js")
    @Styles.Render("~/Content/GooutRecord.css")
    @Styles.Render("~/Scripts/PagePaging.js")
    Layout = "~/Views/Shared/_LayoutPageMu.cshtml";

     
}
 
<div class="Content_R">
    <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
      <div class="main_query">
        卡片号码:<input id="queryCardNO" type="text" validate="number"  value=""  />
        车牌号码:<input id="queryCPH" type="text" validate="number"  value="" />
        停车场名称:<input id="queryParkName" type="text" validate="number"  value="" />
	  <button id="queryBtn"   rel="type1" value="查询"   >查询</button>
        <button id="queryBtnGj"   rel="type1" value="高级查询"   >高级查询</button>
			</div>
            
				<div class="tb_info">
					<table id="tb">
						<thead>
							<tr class="tr-title">
								<th>卡片号码</th>
								<th>车牌号码</th>
                                <th>卡片种类</th>
								<th>入场时间</th>
								<th>出场时间</th>
								<th>入场名称</th>
								<th>出场名称</th>
                                <th>入场操作卡号</th>
                                <th>出场操作卡号</th>
                                <th>入场操作员</th>
                                <th>出场操作员</th>
                                <th>入场图片</th>
                                <th>入场人员</th>
                                <th>出场图片</th>
                                <th>出场人员</th>
                                <th>证件图片</th>
                                <th>收费金额</th>
                                <th>卡上余额</th>
                                <th>应收金额</th>
                                <th>收费时间</th>
                                <th>收费人员</th>
                                <th>收费卡号</th>
                                <th>收费口名</th>
                                <th>超时标志</th>
                                <th>超时收费时间</th>
                                <th>超时收费金额</th>
                                <th>车场编号</th>
                                <th>大小标识</th>
                                <th>停车场名称</th>
                                <th>免费原因</th>
                  </tr>
                		</thead>
						<tbody id="group_one">
						</tbody>
					</table>
                   </div>
        <div class="Page_number">
             <div class="Page_number_btn">
             <button id="Print_Btn"   rel="type1" value="导出" >导出Excel</button>
             <button id="Export_Btn"   rel="type1" value="打印" >打印</button> 
             </div> 
             <div id="barcon"></div>
        </div>

     </asp:contentplaceholder>
</div>


Select.js 这个脚本就是通过对control层的数据进行输出,其中重点就是分页技术的实现,代码很清晰

String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,function (m,i) {
            return args[i];
        });
}
//String的静态方法
String.format = function () {
    if (arguments.length == 0)
        return null;

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}','gm');
        str = str.replace(re,arguments[i]);
    }
    return str;

}
var sumCountP = 0;
var pageIndex = 0;
var Find = Class.create();
var IsWork = false;
Find.prototype = {
    initialize: function (options) { },async: false,Get: function (index) {
        // pageIndex = index;
        //验证
        var validate = GoValidate($("#queryBtn").attr("rel"));

        var CardNO = $("#queryCardNO").val();
        var CPH = $("#queryCPH").val();
        var ParkName = $("#queryParkName").val();
        //  var pageIndex = 0;
        var outcount = 0;
        $("#page").html("正在执行查询请稍后...").show();

        $.getJSON("/GOOUTRECORD/FindQuery",{ CardNO: CardNO,CPH: CPH,ParkName: ParkName,pageIndex: index,pageSize: 22 },function (json) {
                  if (json.Success) {
                      var html = "";
                      //填充数据
                      var pagetemp = "<div class=\"c666\"  >查询完毕,共找到 <span id=\"resultcount\">{0}</span> 条有效记录</div>";
                      var temp = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td>{8}</td><td>{9}</td><td>{10}</td><td>{11}</td><td>{12}</td><td>{13}</td><td>{14}</td><td>{15}</td><td>{16}</td><td>{17}</td><td>{18}</td><td>{19}</td><td>{20}</td><td>{21}</td><td>{22}</td><td>{23}</td><td>{24}</td><td>{25}</td><td>{26}</td><td>{27}</td><td>{28}</td><td>{29}</td>";
                      for (var i = 0; i < json.Count; i++) {

                          var o = json.Data[i];
                          html += temp.format(o.CardNO,o.CPH,o.CardType,o.InTime,o.OutTime,o.InGateName,o.OutGateName,o.InOperatorCard,o.OutOperatorCard,o.InOperator,o.OutOperator,o.InPic,o.InUser,o.OutPic,o.OutUser,o.ZJPic,o.SFJE,o.Balance,o.YSJE,o.SFTime,o.SFOperator,o.SFOperatorCard,o.SFGate,o.OvertimeSymbol,o.OvertimeSFTime,o.OvertimeSFJE,o.CarparkNO,o.BigSmall,o.ParkName,o.FreeReason);
                      }
                      $("#tb tbody").html(html);
                      $("#page").html(String.format(pagetemp,json.Count));
                      $("#tb tbody tr:odd").addClass("bgcf8"); //偶数行颜色
                      var Dijipage = pageIndex + 1

                      sumCountP = (json.SumCount % 22 == 0 ? parseInt(json.SumCount / 22) : parseInt(json.SumCount / 22 + 1));
                      var htmlStr = "";
                      htmlStr += "<span>共有记录" + json.SumCount + "条;  共<span id='SumPcount'>" + parseInt(Dijipage) + "/" + sumCountP + "</span>页  " + "</span>";
                      htmlStr += "<a href='javascript:void' onclick='GoToFirstPage()' id='aFirstPage' >首    页</a> ";
                      htmlStr += "<a href='javascript:void' onclick='GoToPrePage()' id='aPrePage' >前一页</a> ";
                      htmlStr += "<a href='javascript:void' onclick='GoToNextPage()' id='aNextPage'>后一页</a> ";
                      htmlStr += "<a href='javascript:void' onclick='GoToEndPage()' id='aEndPage' >尾    页</a> ";
                      htmlStr += "<input type='text' style=margin-right:5px;width:35px; height:20px;/><input  type='button' style=margin-left:5px; value='跳转' onclick='GoToAppointPage(this)' /> ";
                      $("#barcon").html(htmlStr);


                  }
                  else {
                      $("#page").html(json.Message);
                  }
                  if (json.Count > 0) {
                      //$(".result").slideDown("slow");
                      $("div#resultdiv").attr("style","overflow-y: auto; overflow-x: auto;height:400px;display: none;");
                      $("div#resultdiv").slideDown("slow");

                  }
                  else {
                      $("div#resultdiv").attr("style","display: none;");
                  }
                  IsWork = false;
              }
        );
    }
};



$(function () {
    var find = new Find();
    //alert(find.Template);

    $.ajaxSetup({
        cache: false,global: false,type: "POST"
    });

    //$(".Validate").click(function () { return GoValidate($(this).attr("rel")) });

    $("#queryBtn").click(function () { find.Get() });
    $("#queryBtnGj").click(function () { openwindow() });
})


//首页
function GoToFirstPage() {
    var find = new Find();
    pageIndex = 0;
    find.Get(pageIndex)
   // AjaxGetData($("#txtSearch").val(),pageIndex);
}
//前一页
function GoToPrePage() {
    pageIndex -= 1;
    pageIndex = pageIndex >= 0 ? pageIndex : 0;
    var find = new Find();
    find.Get(pageIndex)
   
   // AjaxGetData($("#txtSearch").val(),pageIndex);
}
//后一页
function GoToNextPage() {
    if (pageIndex + 1 < sumCountP) {
        pageIndex += 1;
    }

    var find = new Find();
 
    find.Get(pageIndex)

    //AjaxGetData($("#txtSearch").val(),pageIndex);
}
//尾页
function GoToEndPage() {
    pageIndex = sumCountP - 1;
    var find = new Find();

    find.Get(pageIndex)
    //AjaxGetData($("#txtSearch").val(),pageIndex);
}
//跳转
function GoToAppointPage(e) {
    var page = $(e).prev().val();
    if (isNaN(page)) {
        alert("请输入数字!");
    }
    else {
        var tempPageIndex = pageIndex;
        pageIndex = parseInt($(e).prev().val()) - 1;
        if (pageIndex < 0 || pageIndex >= sumCountP) {
            pageIndex = tempPageIndex;
            alert("请输入有效的页面范围!");
        }
        else {
            var find = new Find();

            find.Get(pageIndex)
            //AjaxGetData($("#txtSearch").val(),pageIndex);
        }
    }
}

$("#queryBtnGj").click(function () { openwindow() });

function openwindow() {
    window.showModalDialog("/Advancedsearch/Index",window,"status:no;scroll:no;dialogWidth:235px;dialogHeight:400px");
}             

下面是Contorter层的数据输出,这些大家都应该很熟悉不过了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using znykt.Models;
using System.Text;
using System.Data.sqlClient;
using System.Data;

namespace znykt.Controllers
{
    public class GOOUTRECORDController : Controller
    {
        //
        // GET: /GOOUTRECORD/

        public ActionResult Index()
        {
            return View();
        }
        public JsonResult FindQuery(string CardNO,string CPH,string ParkName,int pageIndex = 0,int pageSize = 22)
        {
            Models.FindSelectModel result = new Models.FindSelectModel { Count = 0,SumCount=0,Success = true,Data = new List<Models.GooutRecordModel>() };
            try
            {
                DataTable Relustdt = SearchGooutRecordPro(CardNO,CPH,ParkName,pageIndex,pageSize).Tables[0];// SelectMYCARGOOUTRECORD(CardNO,ParkName);

                result.SumCount = Convert.ToInt32(SearchGooutRecordPro(CardNO,pageSize).Tables[1].Rows[0][0].ToString());
                for (int i = 0; i < Relustdt.Rows.Count; i++)
                {
                    Models.GooutRecordModel m = new Models.GooutRecordModel();
                    m.CardNO = Relustdt.Rows[i]["CardNO"].ToString();
                    m.CPH = Relustdt.Rows[i]["CPH"].ToString();
                    m.CardType = Relustdt.Rows[i]["CardType"].ToString();
                    m.InTime = Relustdt.Rows[i]["InTime"].ToString();
                    m.OutTime = Relustdt.Rows[i]["OutTime"].ToString();
                    m.InGateName = Relustdt.Rows[i]["InGateName"].ToString();
                    m.OutGateName = Relustdt.Rows[i]["OutGateName"].ToString();
                    m.InOperatorCard = Relustdt.Rows[i]["InOperatorCard"].ToString();
                    m.OutOperatorCard = Relustdt.Rows[i]["OutOperatorCard"].ToString();
                    m.InOperator = Relustdt.Rows[i]["InOperator"].ToString();
                    m.OutOperator = Relustdt.Rows[i]["OutOperator"].ToString();
                    m.InPic = Relustdt.Rows[i]["InPic"].ToString();
                    m.InUser = Relustdt.Rows[i]["InUser"].ToString();
                    m.OutPic = Relustdt.Rows[i]["OutPic"].ToString();
                    m.OutUser = Relustdt.Rows[i]["OutUser"].ToString();
                    m.ZJPic = Relustdt.Rows[i]["ZJPic"].ToString();
                    m.SFJE = Relustdt.Rows[i]["SFJE"].ToString();
                    m.Balance = Relustdt.Rows[i]["Balance"].ToString();
                    m.YSJE = Relustdt.Rows[i]["YSJE"].ToString();
                    m.SFTime = Relustdt.Rows[i]["SFTime"].ToString();
                    m.SFOperator = Relustdt.Rows[i]["SFOperator"].ToString();
                    m.SFOperatorCard = Relustdt.Rows[i]["SFOperatorCard"].ToString();
                    m.SFGate = Relustdt.Rows[i]["SFGate"].ToString();
                    m.OvertimeSymbol = Relustdt.Rows[i]["OvertimeSymbol"].ToString();
                    m.OvertimeSFTime = Relustdt.Rows[i]["OvertimeSFTime"].ToString();
                    m.OvertimeSFJE = Relustdt.Rows[i]["OvertimeSFJE"].ToString();
                    m.CarparkNO = Relustdt.Rows[i]["CarparkNO"].ToString();
                    m.BigSmall = Relustdt.Rows[i]["BigSmall"].ToString();
                    m.ParkName = Relustdt.Rows[i]["ParkName"].ToString();
                    m.FreeReason = Relustdt.Rows[i]["FreeReason"].ToString();

                    result.Data.Add(m);
                }
                result.Count = result.Data.Count;
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Message = e.Message;
                return Json(result,JsonRequestBehavior.AllowGet);
            }
            return Json(result,JsonRequestBehavior.AllowGet);
        }
          dbHelper dbsql = new dbHelper();

        #region 数据查询 用户密码是是否存在
        public DataSet SearchGooutRecordPro(string CardNO,int pageIndex,int pageSize)
        {
            sqlConnection conn =  dbsql.Getconn() ;
            conn.Open();
            sqlCommand cmd = new sqlCommand();
            cmd.Connection = conn;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "SearchGooutRecordPro";
            cmd.Parameters.Add(new sqlParameter("@CardNO",CardNO));
              cmd.Parameters.Add(new sqlParameter("@CPH",CPH));
              cmd.Parameters.Add(new sqlParameter("@ParkName",ParkName));

            cmd.Parameters.Add(new sqlParameter("@pageIndex",pageIndex));
            cmd.Parameters.Add(new sqlParameter("@pageSize",pageSize));
            sqlDataAdapter dataAdapter = new sqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                dataAdapter.Fill(ds);
            }
            catch (Exception)
            {

            }
            finally
            {
                if (dataAdapter != null)
                {
                    dataAdapter.Dispose();
                }
                if (cmd != null)
                {
                    cmd.Dispose();
                }
                if (conn != null)
                {
                    conn.Dispose();                
                }
            }
            return ds;
        }



 
         



      
        public DataTable SelectMYCARGOOUTRECORD(string CardNO,string ParkName )
        {

            //StringBuilder strsql = new StringBuilder();
            //strsql.Append("select * from View_MYCARGOOUTRECORD where CardNO like '%@CardNO%'   and CPH  like '%@CPH%'   and ParkName like '%@ParkName%' ");

            //sqlParameter[] params_add = { 
            //                             new sqlParameter("@CardNO",sqlDbType.VarChar),//                                new sqlParameter("@CPH",//                                   new sqlParameter("@ParkName",//                             };
            //params_add[0].Value = CardNO;
            //params_add[1].Value = CPH;
            //params_add[2].Value = ParkName;

            StringBuilder strsql = new StringBuilder();
            strsql.Append("select * from View_MYCARGOOUTRECORD where   1=1  ");

            List<string> ltstr = new List<string>();

            if (CardNO != "")
            {
                ltstr.Add(" CardNO like '%"+CardNO+"%'");
            }
            if (CPH != "")
            {
                ltstr.Add(" CPH like %' + CPH + '%");
            }
            if (ParkName != "")
            {
                ltstr.Add(" ParkName like %' + ParkName + '%");
            }
            if (ltstr.Count>1)
            {strsql.Append( string.Join(" and ",ltstr)) ;
            }
            if (ltstr.Count == 1)
            {
                strsql.Append(" and "+ltstr[0]);
            }
            

            DataTable dt = dbsql.GetTable(strsql.ToString());
            return dt;
        }

        #endregion

    }
}

至于项目中的mode就不一一写出来了。

原文链接:https://www.f2er.com/ajax/164758.html

猜你在找的Ajax相关文章