【问题标题】:Remember (persist) the filter, sort order and current page of Table in MVC 5 EF 6在 MVC 5 EF 6 中记住(持久化)Table 的过滤器、排序顺序和当前页
【发布时间】:2015-04-20 23:34:23
【问题描述】:

所以基本上我在本教程的帮助下完成了所有的排序、过滤和分页,这非常非常方便,因为我对这种材料非常陌生。 - http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SunsUniversity.Models;
using SunsUniversity.DAL;
using PagedList;
using PagedList.Mvc;

namespace SunsUniversity.Controllers
{
    public class StudentController : Controller
    {
        private SchoolContext db = new SchoolContext();

        // GET: /Student/
        public ViewResult Index()
        {
            var students = from s in db.Students
                           select s;
            return View(students.ToList());
        }
        // GET: /Student/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // GET: /Student/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Student/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include="ID,LastName,FirstMidName,EnrollmentDate")] Student student)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    db.Students.Add(student);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
            }
            catch (DataException /* dex */)
            {
                //Log the error (uncomment dex variable name and add a line here to write a log.
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }
            return View(student);
        }

        // GET: /Student/Edit/5
        public ActionResult Edit(int? id)
        {
            var model = TempData["Index"];
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: /Student/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include="ID,LastName,FirstMidName,EnrollmentDate")] Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }

        // GET: /Student/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }

        // POST: /Student/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

索引:

@model IEnumerable<SunsUniversity.Models.Student>

@{
    ViewBag.Title = "Students";
}

<h2>@ViewBag.Title</h2>

<p class="indexOptions">
    @Html.ActionLink("Back", "Index", "Home")  @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-striped table-hover">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstMidName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EnrollmentDate)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.FirstMidName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.EnrollmentDate)
        </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>
        }
    </tbody>
    <tfoot>
        <tr>
            <th class="filterable"></th>
            <th></th>
            <th class="filterable"></th>
            <th class="filterable"></th>
            <th></th>
            <th></th>
        </tr>
    </tfoot>

</table>

@section Outro{
    <script>
        $(document).ready(function () {
            var table = $('.table').DataTable();

            $(".table tfoot th").each(function (i) {
                if ($(this).hasClass("filterable")) {

                    var select = $('<select class="form-control"><option value="">Filter by</option></select>')
                    .appendTo($(this).empty())
                    .on('change', function () {
                        var val = $(this).val();

                        table.column(i)
                            .search(val ? '^' + $(this).val() + '$' : val, true, false)
                            .draw();
                    });

                    table.column(i).data().unique().sort().each(function (d, j) {
                        if (d.length > 0) {

                            select.append('<option value="' + d + '">' + d + '</option>');

                        }

                    });

                }
            });
        });
    </script>
}

现在我的问题是: 我的应用程序用户询问包含表格的页面是否可以记住表格的过滤器、排序顺序和当前页面(因为当他们单击表格项目执行任务然后返回到它时,他们会喜欢它是“他们离开时”)

Cookies 似乎是前进的方向,但在这个阶段,如何让页面加载它们并将它们设置在表中之前,它会发出第一个数据请求,这有点超出我的能力。

有没有人有这方面的经验?谢谢!

可以在索引文件的末尾添加一些东西

保存首选项:从$(window).unload(function(){ ... });调用

加载首选项:从$(document).ready(function(){ ... });调用

【问题讨论】:

标签: c# asp.net entity-framework asp.net-mvc-4 asp.net-mvc-5


【解决方案1】:

最简单的方法是将要访问的过滤器、排序和页面保存在会话存储、cookie 或视图袋中。您将在返回页面时将所有调用的参数发送回服务器。 EF 不支持您想要的操作,因为它只关心获取和设置数据。您必须管理代码中的分页、排序和过滤。

您引用的示例通过使用PagedList(一个nuget包)的这些参数来处理这个问题

public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)

参数就是他们所说的,并在您导航到的每个页面上发回。

完整方法代码:

public ViewResult 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;

   var students = from s in db.Students
                  select s;
   if (!String.IsNullOrEmpty(searchString))
   {
      students = students.Where(s => s.LastName.Contains(searchString)
                             || s.FirstMidName.Contains(searchString));
   }
   switch (sortOrder)
   {
      case "name_desc":
         students = students.OrderByDescending(s => s.LastName);
         break;
      case "Date":
         students = students.OrderBy(s => s.EnrollmentDate);
         break;
      case "date_desc":
         students = students.OrderByDescending(s => s.EnrollmentDate);
         break;
      default:  // Name ascending 
         students = students.OrderBy(s => s.LastName);
         break;
   }

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

【讨论】:

  • 对不起,我觉得我说得不够清楚。从一个页面导航到另一个页面时如何保存数据?
  • 你可以通过在 Viewmodel 中传递一个模型来做到这一点,或者我会考虑使用 Jquery dataTable 来代替它,因为它已经为你处理了它。 [链接]datatables.net
猜你喜欢
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 1970-01-01
  • 2015-03-21
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多