使用PagedList.MVC和Bootstrap模态部分问题

时间:2015-12-16 18:52:57

标签: ajax asp.net-mvc-4 twitter-bootstrap-3 bootstrap-modal

自学MVC所以我想完成的第一个项目是一个使用Bootstraps模态形式的简单CRUD应用程序。

我试图将此学习项目的要求尽可能地作为RealWorld ...因此

  • 使用分页搜索(理想情况下自动填充,不需要提交按钮)
  • 维护当前搜索参数
  • 使用模态表格的CRUD
  • 通过AJAX潜在加载?

我基本上将以下两个项目融合到一个有效的应用程序中。

我对应用程序有一些问题...首先,在我的HttpPostActionResult中,如果我返回PartialView(“_ DetailPaged”),_DetailPage部分告诉我模型为空。因为_detailPage正在寻找PagedList.IPagedList的模型,所以我理论上必须从Index操作中重新运行代码。

所以,我试图返回RedirectToAction(“Index”),只要模型能够正确加载,它就可以工作,但是,因为我正在重新加载我的视图,UI的某些部分会重复出现。 / p>

理想情况下,我希望能够通过ajax加载搜索并仅更新详细信息部分 我想允许用户在不使用提交按钮的情况下搜索表格,因此满足上述要求,最后,我希望能够返回带有搜索参数的查询,即使在编辑或添加之后也是如此。

作为奖励,我想清理搜索查询以仅返回数据的子集,即这10条记录,其中包含关于如何查询下一个或前一个10的书签。

任何建议都将不胜感激。

我的观点

<div id="main-div">
<div class="clearfix">&nbsp;</div>
<div class="clearfix">&nbsp;</div>
<div class="container">

    <a href="@Url.Action("Add", "MVCPager2")" id="Add" class="btn btn-primary"><i class="glyphicon glyphicon-plus"></i>&nbsp;Create New</a>
    <div id="div-record">
        @Html.Partial("_DetailPaged", Model)      
    </div>
</div>

<div class="modal fade" id="Add-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">New Student</h4>
            </div>
            <div class="divForAdd">
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="Edit-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">Update Student</h4>
            </div>
            <div class="divForUpdate">
            </div>
        </div>
    </div>
</div>

部分视图

@model PagedList.IPagedList<Employee>
@using PagedList.Mvc;

@using (Html.BeginForm("Index", "MVCPager", FormMethod.Get))

        {
            <p>
                Find by name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)

                <input type="submit" value="Search" />
            </p>
        }
<div class="table-responsive">
<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.FirstName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.LastName)
                </td>
                <td>
                    <a href="@Url.Action("Edit", "Home", new { ID = item.EmployeeID })" class="editDialog"><i class="fa fa-pencil-square-o"></i>&nbsp;Edit</a>
                </td>
                <td>
                    @Ajax.ActionLink("Delete", "Delete", "Home", new { @ID = item.EmployeeID }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div-record" }, new { @class = "fa fa-trash-o" })
                </td>
            </tr>
        }
    </tbody>
</table>
<br />
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))

</div>

<script>
$(document).ready(function () {
    $('#Add').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForAdd').html(response);
        });
        $('#Add-Model').modal({
            backdrop: 'static',
        }, 'show');
    });
    $('.editDialog').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForUpdate').html(response);
        });
        $('#Edit-Model').modal({
            backdrop: 'static',
        }, 'show');
    });
});
</script>

我的控制器

public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewBag.CurrentFilter = searchString;

        IEnumerable<Employee> Employees;
        using (NorthwindEntities ctx = new NorthwindEntities())
        {
            Employees = ctx.Employees.ToList();
        }

        if (!String.IsNullOrEmpty(searchString))
        {
            Employees = Employees.Where(s => s.LastName.Contains(searchString)
                                   || s.FirstName.Contains(searchString));
        }

        int pageSize = 10;
        int pageNumber = (page ?? 1);            
        return View(Employees.ToPagedList(pageNumber, pageSize));
    }

    public ActionResult Add()
    {
        return PartialView("_AddPaged");
    }

    [HttpPost]
    public ActionResult Add(Employee model)
    {
        List<Employee> Employees = new List<Employee>();
        if (ModelState.IsValid)
        {
            using (NorthwindEntities ctx = new NorthwindEntities())
            {
                Employee _employee = new Employee
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName
                };
                ctx.Employees.Add(_employee);

                try
                {
                    ctx.SaveChanges();
                }
                catch (DbEntityValidationException ex)
                {
                    // Retrieve the error messages as a list of strings.
                    var errorMessages = ex.EntityValidationErrors
                            .SelectMany(x => x.ValidationErrors)
                            .Select(x => x.ErrorMessage);

                    // Join the list to a single string.
                    var fullErrorMessage = string.Join("; ", errorMessages);

                    // Combine the original exception message with the new one.
                    var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                    // Throw a new DbEntityValidationException with the improved exception message.
                    throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
                }
                Employees = ctx.Employees.ToList();
            }
        }
        return RedirectToAction("Index");
        //return PartialView("_DetailPaged");
    }

1 个答案:

答案 0 :(得分:0)

使用此JavaScript进行模型弹出式完成。

在你的脚本中制作一个App.js. 并在那里复制代码。

<强> MyApp.js

$(document).ready(function () {
    $('#add').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForAdd').html(response);
        });
        $('#Add-Model').modal({
            backdrop: 'static',
        }, 'show');
    });


    $('.openDialog-Edit').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForCreate').html(response);
        });

        $('#Edit-Model').modal({
            backdrop: 'static',
        }, 'show');

    });

    $('.openDialog-Delete').click(function (event) {
        event.preventDefault();
        $.get(this.href, function (response) {
            $('.divForDelete').html(response);
        });

        $('#Delete-Model').modal({
            backdrop: 'static',
        }, 'show');

    });
});