MVC 分页在 AJAX 表单中不起作用

问题描述 投票:0回答:2

我正在尝试使用 MVC4.Paging nuget 包实现 ASP.NET MVC 分页。

问题: 它可以在在线演示中运行,也可以在下载源代码中运行。然而,我无法找到为什么它在我的特定项目中无法通过 AJAX 工作。在我的项目中,它通过完整的回发方法工作,但不是 Ajax。

我什至尝试复制

Index
操作方法以及
Index
_AjaxEmployeeList
视图 (.cshtml) 文件(.js 除外)。

注意:在我的解决方案中,它不是示例中所示的引导程序。另外,我的控制器名称是

AdminController
,而在示例中它是
HomeController

在我的解决方案中,我需要它在 AJAX 方法中工作,如示例中所示。

请帮助:
1. 如何找到不工作的根本原因?
2. 如何使其发挥作用?

.
我的解决方案代码(我尝试在示例的解决方案中重现):

索引.cshtml

@using MvcPaging
@model IPagedList<MvcPagingDemo.Models.Employee>
@{
    ViewBag.Title = "MVC 4 Paging With Ajax Bootstrap";
}
<div class="row-fluid">
    <div class="span6">
        <h2>
            Ajax Paging With Bootstrap In MVC 4
        </h2>
    </div>
    <div class="span6">
        <div class="alert alert-info">
            The pager also supports area's. @Html.ActionLink("Ajax paging in an area", "Index", "Admin", new { Area = "AreaOne" }, new { @class = "btn btn-success" })</div>
    </div>
</div>
<div class="clearfix">
</div>
@using (Ajax.BeginForm("Index", "Admin",
                            new AjaxOptions { UpdateTargetId = "grid-list", HttpMethod = "get", LoadingElementId = "loading", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" },
                            new { id = "frm-search" }))
{
    <div class="input-append">
        <input class="span2" id="appendedInputButton" type="text" name="employee_name" placeholder="Name" />
        <button class="btn" type="submit">
            <i class="icon-search"></i>&nbsp;Search</button>
    </div>
    <div id="grid-list">
        @{ Html.RenderPartial("_AjaxEmployeeList", Model); }
    </div>
}
<script type="text/javascript">

    function beginPaging(args) {
        // Animate
        $('#grid-list').fadeOut('normal');
    }

    function successPaging() {
        // Animate
        $('#grid-list').fadeIn('normal');
        $('a').tooltip();
    }

    function failurePaging() {
        alert("Could not retrieve list.");
    }

</script>

_AjaxEmployeeList.cshtml

@using MvcPaging
@model IPagedList<MvcPagingDemo.Models.Employee>
<table class="table table-bordered table-hover">
    <thead>
        <tr>
            <th>
                ID
            </th>
            <th>
                Name
            </th>
            <th>
                Email
            </th>
            <th>
                Phone
            </th>
            <th>
                City
            </th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        { 
            <tr>
                <td>
                    @item.ID
                </td>
                <td>
                    @item.Name
                </td>
                <td>
                    @item.Email
                </td>
                <td>
                    @item.Phone
                </td>
                <td>
                    @item.City
                </td>
            </tr>
        }
    </tbody>
</table>
<div class="pager1">
    @Html.Raw(Ajax.Pager(
            new Options
            {
                PageSize = Model.PageSize,
                TotalItemCount = Model.TotalItemCount,
                CurrentPage = Model.PageNumber,
                ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous", Page = "P" },
                ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
                TooltipTitles = new TooltipTitles() { Next = "Next page", Previous = "Previous page", Page = "Page {0}." },
                Size = Size.normal,
                Alignment = Alignment.centered,
                IsShowControls = true,
                IsShowFirstLast = true,
                CssClass = ""
            },
            new AjaxOptions
            {
                UpdateTargetId = "grid-list",
                OnBegin = "beginPaging",
                OnSuccess = "successPaging",
                OnFailure = "failurePaging"
            }, new { controller = "Admin", action = "Index", employee_name = ViewData["employee_name"] }))
    <div class="well">
        Showing <span class="badge badge-success">@Model.ItemStart</span> to <span class="badge badge-success">@Model.ItemEnd</span>
        of <span class="badge badge-info">@Model.TotalItemCount</span> entries</div>
</div>

AdminController.cs

public class AdminController : Controller
{
    private const int defaultPageSize = 3;
    private IList<Employee> allEmployee = new List<Employee>();
    private string[] name = new string[4] { "Will", "Johnny", "Zia", "Bhaumik" };
    private string[] phone = new string[4] { "1-274-748-2630", "1-762-805-1019", "1-920-437-3485", "1-562-653-8258" };
    private string[] email = new string[4] { "[email protected]", "[email protected]", "[email protected]", "[email protected]" };
    private string[] city = new string[4] { "Wigtown", "Malderen", "Las Vegas", "Talence" };


    public AdminController()
    {
        InitializeEmployee();
    }

    private void InitializeEmployee()
    {
        // Create a list of 200 employee.
        int index = 0;

        for (int i = 0; i < 200; i++)
        {
            var employee = new Employee();
            //int categoryIndex = i % new Random().Next(1, 5);
            //if (categoryIndex > 3)
            //    categoryIndex = 3;
            index = index > 3 ? 0 : index;
            employee.ID = i + 1;
            employee.Name = name[index];
            employee.Phone = phone[index];
            employee.Email = email[index];
            employee.City = city[index];
            allEmployee.Add(employee);
            index++;
        }
    }

    public ActionResult Index(string employee_name, int? page)
    {
        ViewData["employee_name"] = employee_name;
        int currentPageIndex = page.HasValue ? page.Value : 1;
        IList<Employee> employees = this.allEmployee;

        if (string.IsNullOrWhiteSpace(employee_name))
        {
            employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
        }
        else
        {
            employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
        }



        //var list = 
        if (Request.IsAjaxRequest())
            return PartialView("_AjaxEmployeeList", employees);
        else
            return View(employees);
    }

    public ActionResult Paging(string employee_name, int? page)
    {
        ViewData["employee_name"] = employee_name;
        int currentPageIndex = page.HasValue ? page.Value : 1;
        IList<Employee> employees = this.allEmployee;

        if (string.IsNullOrWhiteSpace(employee_name))
        {
            employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
        }
        else
        {
            employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
        }

        return View(employees);
    }
}

_Layout.cshtml中的JS引用

enter image description here

c# asp.net-mvc asp.net-mvc-4 pagination asp.net-ajax
2个回答
0
投票

您还没有描述它到底是如何不起作用的。但我会猜测可能导致您出现问题的最常见问题

  1. 确保您确实引用了正确的 java 脚本文件。将它们放在文件夹中是不够的,您的页面必须链接到它们。

请参阅以下链接以了解如何在页面上引用脚本。 http://www.w3schools.com/tags/att_script_src.asp

确保输入正确的路径。

确保引用 *ajax.js 文件以使 ajax 与任何其他所需文件一起工作。


0
投票

终于找到解决办法了。

由于我使用了

jquery-1.11.1.js
,在脚本文件
jquery.unobtrusive-ajax.js
中,我必须将对 .live() 的调用替换为 .on().

但是简单的查找和替换并不是正确的方法,我后来发现。我从其他来源发现,我必须完全更改这些代码行,因为 .on() 有效。

我替换了如下代码:

带有 .live() 函数的非工作代码:

$("a[data-ajax=true]").live("click", function (evt) {
    debugger;
    evt.preventDefault();
    asyncRequest(this, {
        url: this.href,
        type: "GET",
        data: []
    });
});

$("form[data-ajax=true] input[type=image]").live("click", function (evt) {
    debugger;
    var name = evt.target.name,
        $target = $(evt.target),
        form = $target.parents("form")[0],
        offset = $target.offset();

    $(form).data(data_click, [
        { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
        { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
    ]);

    setTimeout(function () {
        $(form).removeData(data_click);
    }, 0);
});

$("form[data-ajax=true] :submit").live("click", function (evt) {
    debugger;
    var name = evt.target.name,
        form = $(evt.target).parents("form")[0];

    $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

    setTimeout(function () {
        $(form).removeData(data_click);
    }, 0);
});

$("form[data-ajax=true]").live("submit", function (evt) {
    debugger;
    var clickInfo = $(this).data(data_click) || [];
    evt.preventDefault();
    if (!validate(this)) {
        return;
    }
    asyncRequest(this, {
        url: this.action,
        type: this.method || "GET",
        data: clickInfo.concat($(this).serializeArray())
    });
});

使用 .on() 函数的工作代码:

$(document).on("click", "a[data-ajax=true]", function (evt) {
    evt.preventDefault();
    asyncRequest(this, {
        url: this.href,
        type: "GET",
        data: []
    });
});

$(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
    var name = evt.target.name,
        $target = $(evt.target),
        form = $target.parents("form")[0],
        offset = $target.offset();

    $(form).data(data_click, [
        { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
        { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
    ]);

    setTimeout(function () {
        $(form).removeData(data_click);
    }, 0);
});

$(document).on("click", "form[data-ajax=true] :submit", function (evt) {
    var name = evt.target.name,
        form = $(evt.target).parents("form")[0];

    $(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);

    setTimeout(function () {
        $(form).removeData(data_click);
    }, 0);
});

$(document).on("submit", "form[data-ajax=true]", function (evt) {
    var clickInfo = $(this).data(data_click) || [];
    evt.preventDefault();
    if (!validate(this)) {
        return;
    }
    asyncRequest(this, {
        url: this.action,
        type: this.method || "GET",
        data: clickInfo.concat($(this).serializeArray())
    });
});

谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.