MVC 3 基本操作列表分页查询

Mvc3中默认提供了一个WebGrid扩展方法,这个方法实现列表功能是非常的强大,但是的asp.net中的GridView一样,它的分页查询都是基于内存的,这样对服务器的性能影响就比较大,在网上也看到很实现分页的代码,但能运行起来的也是很有限,根据最近这段时间的学习,作一个学习笔记。

 

生成效果如下(使用了MVCPager):

image

 

此分页是通过jquery异步调用生成的,下面来看看怎样达到这样的效果:

还是打开上次准备好的项目,引用MvcPager程序集,最好从网站上下载最新的代码自己编译,下载地址为“http://www.webdiyer.com/Controls/MvcPager/”,我当时就遇到过下载到的dll引用的MVC的版本和我本地的不一样,上面使用的MVCPager,我修改了一下输出的地址,如下所示:

image

 

调用了自定义的函数(“LoadMvcPage”),修改过程如下:

打开MvcPager中PageBuiler.cs文件,修改函数“GeneratePagerElement,GenerateAnchor”为如下内容:

   1: private string GenerateAnchor(PagerItem item)
   2:         {           
   3:  
   4:             return GeneratePagerElement(item).ToHtmlString();
   5:         }
   6: private MvcHtmlString GeneratePagerElement(PagerItem item)
   7:         {
   8:             //pager item link
   9:             string url = GenerateUrl(item.PageIndex);
  10:             if (item.Disabled) //first,last,next or previous page
  11:                 return CreateWrappedPagerElement(item, String.Format("<a disabled=\"disabled\">{0}</a>", item.Text));
  12:             return CreateWrappedPagerElement(item,
  13:                                              string.IsNullOrEmpty(url)
  14:                                                  ? _html.Encode(item.Text)
  15:                                                  : String.Format("<a href=\"javascript:{2}('{0}');\">{1}</a>", url, item.Text,loadPageAction));
  16:         }

 

修改HomeConroller下的List Action为如下内容:

 

   1: [OutputCache(Duration = 0)]
   2:         public ActionResult List(int? page)
   3:         {
   4:             int current = 1;
   5:             if (page != null)
   6:             {
   7:                 current = page.Value;
   8:             }
   9:             var manager = new NoteManager();
  10:             Collection<Note> data = manager.GetAll();
  11:             var list = new PagedList<Note>(data.Skip((current - 1) * 4).Take(4), current, 4, data.Count);
  12:             return PartialView(list);
  13:         }

 

修改Common.js文件内容为:

   1: var Success = 0;
   2: var AlertError = 2;
   3: function DialogObject(dialogId, formId, addUrl, editUrl, saveUrl, ajaxPostFunction, loadSuccessCallBack) {
   4:     this._dialogId = "#" + dialogId;
   5:     this._formId = "#" + formId;
   6:     this._saveUrl = saveUrl;
   7:     this._addUrl = addUrl;
   8:     this._editUrl = editUrl;
   9:     this._ajaxPostFunction = ajaxPostFunction;
  10:     this._loadSuccessCallBack = loadSuccessCallBack;
  11: };
  12:  
  13: DialogObject.prototype.dialogLoad = function (width, height, modal) {
  14:     $(this._dialogId).dialog({
  15:         autoOpen: false, //对话框的是否自动打开
  16:         width: width, //宽高
  17:         height: height,
  18:         modal: modal == undefined ? true : modal, //模态对话框
  19:         buttons: {//自定义对话框的按钮信息
  20:             "保存": this._ajaxPostFunction,
  21:             "返回": this._closedialog()
  22:         }
  23:     });
  24: };
  25: DialogObject.prototype.loadEdit = function (id) {
  26:  
  27:     $(this._dialogId).html("")
  28:         .dialog("option", "title", "编辑")
  29:         .load(this._editUrl + "/" + id, this._openDialog());
  30:  
  31: };
  32: DialogObject.prototype.loadAdd = function () {
  33:     $(this._dialogId).html("")
  34:             .dialog("option", "title", "新增")
  35:             .load(this._addUrl, this._openDialog());
  36: };
  37: DialogObject.prototype._openDialog = function () {
  38:     return new Function("$('" + this._dialogId + "').dialog('open');");
  39: };
  40: DialogObject.prototype._closedialog = function () {
  41:     return new Function("$('" + this._dialogId + "').dialog('close');");
  42: };
  43:  
  44: DialogObject.prototype.checkFormData = function () {
  45:     var b = $(this._formId);
  46:     b.submit();
  47:     if (b.validate().numberOfInvalids() > 0) {
  48:         return false;
  49:     }
  50:  
  51:     return true;
  52: };
  53:  
  54: DialogObject.prototype.defaultAjaxPostFunction = function () {
  55:     if (!this.checkFormData()) {
  56:         return;
  57:     }
  58:     this._postFunction($(this._formId).serialize(), function (dlgObject, formObject, data, dlg) {
  59:         if (data.Success == true) {
  60:             dlgObject.dialog("close");
  61:             if (dlg._loadSuccessCallBack != null) {
  62:                 dlg._loadSuccessCallBack();
  63:             }
  64:         }
  65: //        else if (data.Success == AlertError) {
  66: //            alert(data.data);
  67: //        }
  68: //        else {
  69: //            formObject.html(data.data);
  70: //        }
  71:     }, this);
  72: };
  73: DialogObject.prototype.postFunction = function (formData, successCallback) {
  74:     this._postFunction(formData, successCallback, this);
  75: };
  76:  
  77: DialogObject.prototype._postFunction = function (formData, successCallback, dlg) {
  78:     $.post(dlg._saveUrl,
  79:                 formData,
  80:                 function (data, textStatus) {
  81:                     switch (textStatus) {
  82:                         case 
  83:                                 "timeout":
  84:                             break;
  85:                         case "error":
  86:                             break;
  87:                         case "notmodified":
  88:                             break;
  89:                         case "success":
  90:                             successCallback($(dlg._dialogId), $(dlg._formId), data, dlg);
  91:                             break;
  92:                         case "parsererror":
  93:                             break;
  94:                         default:
  95:                             break;
  96:                     }
  97:  
  98:                 });
  99:  
 100: };

 

修改List视图为如下内容:

   1: @using Webdiyer.WebControls.Mvc
   2: @model PagedList<MvcSample.Models.Note>
   3:        <ul class="NotesList">    
   4:        @foreach (var note in Model)    
   5:        {   
   6:             <li>        @note.Title <br />        @note.Body <br />       
   7:         <span class="EditLink" noteid="@note.Id">Edit</span>    
   8:         </li>   
   9:        }
  10:        </ul>
  11:  
  12:        <br />
  13: @*分页控件显示的地方一定要放在刷新的div里面,不然会出现双重控件*@
  14: <div style="text-align:right;">
  15: @Html.AjaxPager(Model, new PagerOptions() 
  16: { PageIndexParameterName = "page", ShowDisabledPagerItems = true, 
  17:     AlwaysShowFirstLastPageNumber = true, CssClass = "pages" },
  18:         new AjaxOptions { UpdateTargetId = "NoteListBlock" })</div>

 

修改Index视图为如下内容:

   1: @{
   2:     ViewBag.Title = "Home Page";
   3: }
   4: <h2>
   5:     Notes</h2>
   6: <div id="NoteListBlock">
   7: </div>
   8: <span class="AddLink">Add New Note</span>
   9: <div id="NoteDialog" title="" class="Hidden">
  10: </div>
  11: <script src="@Url.Content("~/Scripts/Common.js?verion=1")" type="text/javascript"></script>
   1:  
   2: <script type="text/javascript">
   3:     var noteDialog = new DialogObject("NoteDialog", "NoteForm", "/Home/Create", "/Home/Edit", "/Home/Save", ajaxPostFunctionModel, LoadList);
   4:     $(function() {
   5:         noteDialog.dialogLoad(440,330);
   6:         $(".EditLink").live("click", function () {
   7:             var id = $(this).attr("noteid");
   8:             noteDialog.loadEdit(id);
   9:         });
  10:         $(".AddLink").click(function () {
  11:             noteDialog.loadAdd();
  12:         });
  13:  
  14:         LoadList();
  15:     });
  16:     function ajaxPostFunctionModel() {
  17:         noteDialog.defaultAjaxPostFunction();
  18:     }
  19:     
  20:     function LoadList() {
  21:         LoadMvcPage("/Home/List");
  22:     }
  23:  
  24:     function AddRecord() {
  25:         noteDialog.loadAdd();
  26:         return false;
  27:     }
  28:  
  29:     function LoadMvcPage(url) {
  30:         $("#NoteListBlock").load(url);
  31:     }
</script>

 

到此所有的修改完成,如果完全按照上面的做,就能看页面开始图片的效果。

posted @ 2011-07-23 12:02  cdboy  阅读(3934)  评论(0编辑  收藏  举报