MVC無刷新查詢,PagedList分頁控件使用,導出Excel


使用MVC開發也有一段時間了,總結下無刷新部分視圖的使用、PagedList分頁控件的使用。

@using PagedList
@model StaticPagedList<T>
<style type="text/css">
    .tab-title {
        background-color: #efefef;
        width: 10%;
    }

    .btn-custom {
        padding: 6px 24px !important;
        color: #ffffff !important;
        border-radius: 5px;
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }
</style>
@{

}
<section>
    <div class="container" style="margin-top:10px;padding-top:2em;padding-bottom:4em;">
        @using (Ajax.BeginForm("Index", "Hscode", null,
                        new AjaxOptions()
                        {
                            HttpMethod = "Post",
                            InsertionMode = InsertionMode.Replace,
                            UpdateTargetId = "div-result",
                            OnComplete = "regJs"
                        },
                        new { @class = "form-horizontal", role = "form", id = "ajax-form" }))
        {  <div class="form-group">
            <div class="col-sm-4">
                <input type="text" class="form-control" id="hscode" name="hscode" placeholder="商品編碼">
            </div>
            <div class="col-sm-4">
                <input type="text" class="form-control" id="gname" name="gname" placeholder="商品名稱">
            </div>
            <div class="col-sm-4">
                <button type="submit" class="btn btn-custom btn-sm">
                    <span class="glyphicon glyphicon-search"></span> 查詢
                </button>
                <a href="javascript:void(0)" class="btn btn-custom btn-sm" id="btnExport"><span class="glyphicon glyphicon-download"></span> 導 出</a>
            </div>
        </div>
        }
        <div id="div-result">
            @Html.Partial("_Index", Model)
        </div>
    </div>
</section>

@section scripts{
    <script src="~/Scripts/jquery.nicescroll.min.js"></script>
    <script type="text/javascript">
        function regJs() {
            $("#pager > .pagination-container > .pagination > li > a").click(function () {
                var pageUrl = $(this).attr("href");
                var queryStr = $("#ajax-form").serialize();
                $(this).attr("href", pageUrl + "&" + queryStr);
            });

        }

        regJs();

        $("html").niceScroll({
            cursorcolor: "#ddd",
            cursoropacitymax: 1,
            touchbehavior: false,
            cursorwidth: "10px",
            cursorborder: "0",
            cursorborderradius: "5px"
        });

        $("#btnExport").click(function () {
            var queryStr = $("#ajax-form").serialize();
            location.href = "/Hscode/Export?" + queryStr;
        });
    </script>
}
主視圖
  • 使用@Html.Partial("_Index", Model)在主視圖進行部分視圖的渲染
  • PagedList點擊分頁時如何提交查詢條件?這個問題困擾了下我。

     經網上查資料用如下方法解決:

     $("#pager > .pagination-container > .pagination > li > a").click(function () {
                var pageUrl = $(this).attr("href");
                var queryStr = $("#ajax-form").serialize();
                $(this).attr("href", pageUrl + "&" + queryStr);
            });

       即將表單內容通過URL查詢字符串進行傳遞。

  • 無刷新查詢需要使用的js有:jquery.unobtrusive-ajax
  • 無刷新查詢后會導致js失效,使用OnComplete進行js方法的重新注冊。
@using PagedList
@using PagedList.Mvc
@model StaticPagedList<Hscode>

@if (Model != null && Model.Count > 0)
{

    foreach (var hscode in Model)
    {
        <table class="table table-condensed">
            <tbody>
                <tr>
                    <td class="tab-title" style="border-top:1px dashed #000;">商品編碼</td>
                    <td colspan="5" style="border-top:1px dashed #000;color:#ff0000;">@hscode.Hscode1</td>
                </tr>
                <tr>
                    <td class="tab-title">商品名稱</td>
                    <td colspan="5">@hscode.GName</td>
                </tr>
                <tr>
                    <td class="tab-title">申報要素</td>
                    <td colspan="5">@hscode.DeclarationElements</td>
                </tr>
                <tr>
                    <td class="tab-title">法定第一單位</td>
                    <td>@hscode.Unit1</td>
                    <td class="tab-title">法定第二單位 </td>
                    <td>@hscode.Unit2</td>
                    <td colspan="2"></td>

                </tr>
                <tr>
                    <td class="tab-title">最惠國進口稅率</td>
                    <td>@hscode.ZHGJKSL</td>
                    <td class="tab-title">普通進口稅率</td>
                    <td>@hscode.PTJKSL</td>
                    <td class="tab-title">暫定進口稅率</td>
                    <td>@hscode.ZDJKSL</td>
                </tr>
                <tr>
                    <td class="tab-title">消費稅率</td>
                    <td>@hscode.XFSL</td>
                    <td class="tab-title">出口關稅率</td>
                    <td>@hscode.CKGSL</td>
                    <td class="tab-title">出口退稅率</td>
                    <td>@hscode.CKTSL</td>
                </tr>
                <tr>
                    <td class="tab-title">增值稅率</td>
                    <td>@hscode.ZZSL</td>
                    <td class="tab-title">海關監管條件</td>
                    <td>@hscode.HGJGTJ</td>
                    <td class="tab-title">檢驗檢疫類別</td>
                    <td>@hscode.JYJYLB</td>
                </tr>
                <tr>
                    <td class="tab-title" style="border-bottom:1px dashed #000;">商品描述</td>
                    <td colspan="5" style="border-bottom:1px dashed #000;">@hscode.ProductDesc</td>
                </tr>
            </tbody>
        </table>
    }

    <div style="width:100%;text-align:center">每頁 @Model.PageSize 條記錄,共 @Model.PageCount 頁,當前第 @Model.PageNumber 頁,合計 @Model.TotalItemCount 條記錄</div>
    <div style="width:100%;text-align:center" id="pager">
        @Html.PagedListPager(Model, page => Url.Action("Index", new
   {
       page
   }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new AjaxOptions
   {
       HttpMethod = "Post",
       InsertionMode = InsertionMode.Replace,
       UpdateTargetId = "div-result",
       OnComplete = "regJs"
   }))
    </div>
}
else
{
    <table class="table table-condensed">
        <thead>
            <tr>
                <th class="text-center">不存在符合條件的數據!</th>
            </tr>
        </thead>
    </table>

}
部分視圖
public class HscodeController : Controller
    {
        private BasicModels dbContext = new BasicModels();

        public ActionResult Index(int? page)
        {
            return Query(page);
        }

        [HttpPost]
        public ActionResult Index(int? page, FormCollection form)
        {
            return Query(page, true);
        }

        private ActionResult Query(int? page, bool ajaxQuery = false)
        {
            int pageIndex = page ?? 1;
            int pageSize = Pager.PageSize;

            IQueryable<Hscode> list = Query();

            int totalItemCount = list.Count();
            list = list.OrderBy(o => o.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize);

            StaticPagedList<Hscode> pageData = new StaticPagedList<Hscode>(list, pageIndex, pageSize, totalItemCount);

            if (ajaxQuery)
            {
                return PartialView("_Index", pageData);
            }
            else
            {
                return View("Index", pageData);
            }
        }

        private IQueryable<Hscode> Query()
        {
            IQueryable<Hscode> list = dbContext.Hscode;

            string hscode = Request["hscode"];
            if (hscode != null && !string.IsNullOrEmpty(hscode.Trim()))
            {
                list = list.Where(w => w.Hscode1.Contains(hscode.Trim()));
            }

            string gname = Request["gname"];
            if (gname != null && !string.IsNullOrEmpty(gname.Trim()))
            {
                list = list.Where(w => w.GName.Contains(gname.Trim()));
            }

            return list;
        }

        public void Export()
        {
            IQueryable<Hscode> list = Query();

            DataTable dt = list.Convert();
            string strFileName = string.Format("申報要素_{0}", DateTime.Now.ToString("yyyyMMddHHmmssffffff"));

            ExcelHelper.ExportXlsxByWeb(dt, strFileName);
        }
    }
控制器代碼
  • 分頁控件在視圖中的使用如下

 

  • 使用Entity Framework時,因為要根據查詢條件進行查詢。

     早先使用IEnumerate<Hscode> list = dbContext.Hscode;導致表中全部內容加載到內存中,查詢很慢。

     怎么沒使用延遲加載了?最后經同事指正如下才能做到延遲加載:

     IQueryable<Hscode> list = dbContext.Hscode;

  • 查詢條件過濾數據

     if (Request["hscode"] != null && !string.IsNullOrEmpty(Request["hscode"].Trim()))
     {
            list = list.Where(w => w.Hscode1.Contains(Request["hscode"].Trim()));
      }

      這種寫法是有問題的。不知道大家開發的時候有沒有遇到過?

      有條件查詢的時候會報錯LINQ to Entities 不識別方法 System.String get_Item(System.String)

     修正方法如下:

      string hscode = Request["hscode"];
      if (hscode != null && !string.IsNullOrEmpty(hscode.Trim()))
      {
            list = list.Where(w => w.Hscode1.Contains(hscode.Trim()));
      }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM