【问题标题】:What is the best way to persist filters, paging, sorting in .NET Core MVC在 .NET Core MVC 中持久化过滤器、分页、排序的最佳方法是什么
【发布时间】:2020-08-25 23:08:24
【问题描述】:

我正在开发一个 .NET Core MVC 应用程序。对于我的 CRUD 操作,我有一个基本的 Index.cshtml、Edit.cshtml 和 Create.cshtml 页面。在我的 Index.cshtml 中,我可以对页面进行排序、过滤。我将此信息添加到查询字符串中,例如

https://localhost:5001/admin/myPage?search=my+search+string&page=3

现在,当我编辑一行时,我会跳转到另一页。在编辑页面中,有可能,我需要进一步跳转到其他页面。最后,当我回到我的 Index.cshtml 页面时,我想应用我原来的过滤器。

我知道我可以在页面之间来回传递查询字符串键和值,但这对我来说看起来相当复杂。

实现这一点的最佳方法是什么?

【问题讨论】:

  • 取决于您的应用程序... Cookies/LocalStorage?会话?
  • 您还可以为用户将数据存储在数据库中 - 这样,下次登录时可以记住排序

标签: c# .net-core asp.net-core-mvc


【解决方案1】:

您可以使用会话或 cookie 来存储过滤器、分页和排序值。在 Index action 方法中,您可以检查参数值是否为 null,然后,您可以查询 session 并尝试找到以前存储的值并使用它们来过滤或排序数据。如果参数不为空,则可以更新会话值。

这样的代码(查看排序顺序相关的代码):

    public async Task<IActionResult> Index(string sortOrder,string currentFilter, string searchString, int? pageNumber)
    {
        if (searchString != null)
        {
            pageNumber = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        if(sortOrder != null)
        {
            //if sortOrder is not null, update the session to store the new sort order
            HttpContext.Session.SetString("sortOrder", sortOrder);
        }
        else
        {   //check if session contains the sort order.
            if(HttpContext.Session.GetString("sortOrder") != null)
            {
                //get sortOrder from session
                sortOrder = HttpContext.Session.GetString("sortOrder");
            }
            else
            {
                //session expired or is null, use the default sort order.
            }
        }

        ViewData["CurrentSort"] = sortOrder; 
        ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";


        var projects = from s in _context.Projects
                       select s;
        if (!String.IsNullOrEmpty(searchString))
        {
            projects = projects.Where(s => s.ProName.Contains(searchString));
        }
        switch (sortOrder)
        {
            case "name_desc":
                projects = projects.OrderBy(s => s.ProName);
                break; 
            default:
                projects = projects.OrderBy(s => s.ProID);
                break;
        }

        int pageSize = 3;
        return View(await PaginatedList<Projects>.CreateAsync(projects.AsNoTracking(), pageNumber ?? 1, pageSize));
        
    }

你可以参考下面的代码在asp.net core中配置会话(默认会话超时时间为20分钟,你可以改变它):

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    { 
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromMinutes(30); //set session expire time
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSession();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapRazorPages();
        });
    }
}

更多关于使用会话管理的详细信息,请查看Session and state management in ASP.NET Core

【讨论】:

  • 感谢您的回答!我会检查是否像这样实现它。
猜你喜欢
  • 2021-06-06
  • 2012-04-07
  • 2018-11-30
  • 2018-05-23
  • 2015-04-20
  • 2018-12-19
  • 2021-11-10
  • 2010-10-11
  • 2013-07-29
相关资源
最近更新 更多