ASP.NET MVC中如何持久化Enum下拉框的选中值
解决下拉筛选器选中值持久保留的问题
方案一:使用Session持久化选中值(推荐,会话期间保留)
1. 先启用Session服务(.NET Core)
在Program.cs中添加Session配置:
// 添加Session服务 builder.Services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); // 设置会话超时时间 options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); // 在UseRouting之后、UseAuthorization之前启用Session app.UseSession();
2. 修改FilterController代码
正确存储选中的枚举值到Session:
[HttpPost] public IActionResult Index(PostCategory? postCategory) { List<Post> post; if (postCategory != null) { // 将枚举转为字符串存储到Session HttpContext.Session.SetString("SelectedPostCategory", postCategory.ToString()); post = _context.Posts.Where(c => c.PostCategory == postCategory).ToList(); } else { // 选中"All"时清除Session中的值 HttpContext.Session.Remove("SelectedPostCategory"); post = _context.Posts.ToList(); } _cache.Set("post", post); return View("~/Views/Home/Index.cshtml"); }
3. 修改Filter.cshtml视图
从Session读取选中值并设置下拉框选中状态:
@{ PostCategory? selectedCategory = null; var selectedCategoryStr = Context.Session.GetString("SelectedPostCategory"); // 解析Session中的字符串为枚举类型 if (!string.IsNullOrEmpty(selectedCategoryStr) && Enum.TryParse<PostCategory>(selectedCategoryStr, out var parsed)) { selectedCategory = parsed; } } <div class="col-4"> <form class="w-75 ps-lg-5" asp-controller="Filter" asp-action="Index" id="category"> <div class="input-group"> <select class="form-control" asp-items="@Html.GetEnumSelectList<PostCategory>()" name="postCategory" id="post-filter" asp-for="@selectedCategory"> <option value="">All</option> </select> <button class="btn btn-outline-success me-2" type="submit">Filter</button> </div> </form> </div>
方案二:使用ViewModel传递选中值(临时保留,刷新页面失效)
如果不需要跨页面持久化,仅在提交后保留,可以用ViewModel传递值:
1. 创建FilterViewModel
public class FilterViewModel { public PostCategory? SelectedCategory { get; set; } public List<Post> Posts { get; set; } }
2. 修改Controller代码
[HttpPost] public IActionResult Index(PostCategory? postCategory) { var viewModel = new FilterViewModel(); viewModel.SelectedCategory = postCategory; viewModel.Posts = postCategory != null ? _context.Posts.Where(c => c.PostCategory == postCategory).ToList() : _context.Posts.ToList(); _cache.Set("post", viewModel.Posts); return View("~/Views/Home/Index.cshtml", viewModel); }
3. 修改视图
@model FilterViewModel <div class="col-4"> <form class="w-75 ps-lg-5" asp-controller="Filter" asp-action="Index" id="category"> <div class="input-group"> <select class="form-control" asp-items="@Html.GetEnumSelectList<PostCategory>()" name="postCategory" id="post-filter" asp-for="@Model.SelectedCategory"> <option value="">All</option> </select> <button class="btn btn-outline-success me-2" type="submit">Filter</button> </div> </form> </div>
你之前的Session使用错误说明
- 错误写法
Session["selectedValue"]:.NET Core中没有全局Session对象,必须通过HttpContext.Session访问。 - 错误写法
HttpContext.Session("selectedValue") = postCategory:Session的索引器是[]而非(),且枚举类型不能直接存储,需要先转为字符串,用SetString/GetString方法操作。
内容的提问来源于stack exchange,提问作者ZNAXNOR
相关产品推荐
相关产品推荐

