008. MVC分页和异步

1. 网上得到的一个扩展 HtmlHelper

//namespace MvcCRUDDemo.Models
namespace System.Web.Mvc
{
    public static class MyHtmlHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="currentPage">当前页码</param>
        /// <param name="pageSize">每页显示的条数</param>
        /// <param name="totalCount">总条数</param>
        /// <returns></returns>
        public static HtmlString ShowPageNavigate(this HtmlHelper htmlHelper, int currentPage, int pageSize, int totalCount)
        {
            var redirectTo = htmlHelper.ViewContext.RequestContext.HttpContext.Request.Url.AbsolutePath;
            pageSize = pageSize == 0 ? 3 : pageSize;
            var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数
            var output = new StringBuilder();
            if (totalPages > 1)
            {
                output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>首页</a> ", redirectTo, pageSize);
                if (currentPage > 1)
                {//处理上一页的连接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>上一页</a> ", redirectTo, currentPage - 1, pageSize);
                }
                output.Append(" ");
                int currint = 5;
                for (int i = 0; i <= 10; i++)
                {//一共最多显示10个页码,前面5个,后面5个
                    if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
                    {
                        if (currint == i)
                        {//当前页处理              
                            output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage, pageSize, currentPage);
                        }
                        else
                        {//一般页处理
                            output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>{3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
                        }
                    }
                    output.Append(" ");
                }
                if (currentPage < totalPages)
                {//处理下一页的链接
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>下一页</a> ", redirectTo, currentPage + 1, pageSize);
                }
                output.Append(" ");
                if (currentPage != totalPages)
                {
                    output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1}&pageSize={2}'>末页</a> ", redirectTo, totalPages, pageSize);
                }
                output.Append(" ");
            }
            output.AppendFormat("<label>第{0}页 / 共{1}页</label>", currentPage, totalPages);//这个统计加不加都行
            return new HtmlString(output.ToString());
        }
    }
}

 2. css代码:

    <style type="text/css">
        .paginator
{
  font: 12px Arial, Helvetica, sans-serif;
  padding: 10px 20px 10px 0;
  margin: 0px auto;
}
.paginator a
{
  border: solid 1px #ccc;
  color: #0063dc;
  cursor: pointer;
  text-decoration: none;
}
.paginator a:visited
{
  padding: 1px 6px;
  border: solid 1px #ddd;
  background: #fff;
  text-decoration: none;
}
.paginator, .cpb
{
  border: 1px solid #F50;
  font-weight: 700;
  color: #F50;
  background-color: #ffeee5;
} 
.paginator a:hover
{
  border: solid 1px #F50;
  color: #f60;
  text-decoration: none;
}
.paginator a, .paginator a:visited, .paginator .cpb, .paginator a:hover
{
  float: left;
  height: 16px;
  line-height: 16px;
  min-width: 10px;
  _width: 10px;
  margin-right: 5px;
  text-align: center;
  white-space: nowrap;
  font-size: 12px;
  font-family: Arial,SimSun;
  padding: 0 3px;
}
.paginator label
{
  display:block;  
  float:left;  
}
    </style>

3. 前台引用:

<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.BookName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.BookAuth)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserInfo.UserName)
            </th>
            <th></th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.BookName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.BookAuth)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UserInfo.UserName)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new
           {
               id = item.Id
           }) |
                    @Html.ActionLink("Details", "Details", new
           {
               id = item.Id
           }) |
                    @Html.ActionLink("Delete", "Delete", new
           {
               id = item.Id
           })
                </td>
            </tr>
        }
    </table>
    @*@Html.ShowPageNavigate(Model.Pager.CurrentPageIndex, Model.Pager.PageSize, Model.Pager.RecordCount)*@

    @(Html.ShowPageNavigate((int)ViewData["pageIndex"], (int)ViewData["pageSize"], (int)ViewData["total"]))
    <br />
    分页调用
</body>                     

4. 还要检查下web.config文件中是否有下面的项

  <appSettings>
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

--------------------------------------------------------------------------------------------------------------------------------------------------------------

MVC异步

控制器

namespace MvcCRUDDemo.Controllers
{
    public class AjaxController : Controller
    {
        // GET: Ajax
        public ActionResult Index()
        {
            return View();
        }

        //平常的异步
        public ActionResult Date()
        {
            return Content(DateTime.Now.ToString() + "Date异步显示日期");
        }

        //异步
        public ActionResult GetDate()
        {
            return Content(DateTime.Now.ToString()+"异步显示日期");
        }
    }
}

 前台

<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <script src="~/Scripts/jquery-1.8.0.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script type="text/javascript">
        $(function () {
            //这个是mvc异步加载时候的图片的问题
            $("#loadingDiv").css("display", "none");
            $("#bntAJAX").click(function () {
                $.ajax({
                    url: "/Ajax/Date",
                    type: "post",
                    data: {},
                    success: function (data) {
                        $("#Text1").val(data)
                    }
                });
            });
        });
        function afterSuccess(data) { alert(data); $("#resultTxt").val(data) }
    </script>
</head>
<body>
    <div>
        <input type="button" value="获取时间" id="bntAJAX" />
        <input id="Text1" type="text" /><br /><br /><br /><br />
        <p>mvc自带的异步请求方式</p>
        Mvc5中书写方式<br />去. . . .
            @Ajax.BeginForm("GetDate", "Ajax", new AjaxOptions()
          {
              Confirm = "您确定提交吗?",
              HttpMethod = "Post",
              UpdateTargetId = "resultTxt",
              InsertionMode = InsertionMode.Replace,
              OnSuccess = "afterSuccess",
              LoadingElementId = "loadingDiv"
          })
        . . .  .哪里. . . . <br />
        <div id="loadingDiv"><img src="~/images/timg.gif" /></div>
        
        <input type="submit" value="获取时间2"  />
        <input id="resultTxt" type="text" value="我是默认值" />
    </div>
</body>

 结果:

Ajax Options 对应表

 

 

 <form action="/Ajax/GetDate" data-ajax="true" data-ajax-confirm="您确定提交吗?" data-ajax-loading="#loadingDiv" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-success="afterSuccess" data-ajax-update="#resultTxt" id="form0" method="post">

 解决上图遗留的问题, 今天晚上测试出来了, 知道问题出现在什么地方了

将上面ajax的代码做一点修改

 @using (Ajax.BeginForm("GetDate", "Ajax", new AjaxOptions()
        {
            Confirm = "您确定提交吗?",
            HttpMethod = "Post",
            UpdateTargetId = "resultTxt",
            InsertionMode = InsertionMode.Replace,
            OnSuccess = "afterSuccess",
            LoadingElementId = "loadingDiv"
        }))
        {
            <input type="submit" value="获取时间2" />
            <input id="resultTxt" type="text" value="我是默认值" />
        }

 

posted on 2017-02-16 16:01  印子  阅读(144)  评论(0)    收藏  举报

导航