如何解决在.NET Core MVC中持久保存过滤器,分页和排序的最佳方法是什么
我正在开发.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页面时,我想应用原始过滤器。
我知道我可以在页面之间来回传递查询字符串键和值,但这对我来说似乎很复杂。
实现此目标的最佳方法是什么?
解决方法
您可以使用会话或cookie来存储过滤器,分页和排序值。在“索引”操作方法中,可以检查参数值是否为null,然后可以查询会话并尝试查找以前存储的值,然后使用它们来过滤或排序数据。如果参数不为null,则可以更新会话值。
这样的代码(检查与排序顺序有关的代码):
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核心中配置会话(默认情况下,会话超时为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。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。