ASP.NET Core货币下拉框页面重载后选中值恢复默认问题问询
问题根因
- 后端SetCurrency接口参数名与表单提交的字段名不匹配,存在模型绑定失败风险
- Select列表项的选中判断逻辑与绑定值不统一,Value用
DisplayLocale但Selected判断用Id - 页面加载时未主动读取Cookie中存储的货币值赋值给视图模型,渲染时默认使用初始值
修复步骤
1. 修正后端SetCurrency接口参数与逻辑
将接收参数名与表单select的name属性对齐,同时增加Cookie必要标记避免合规策略拦截:
[HttpPost] public IActionResult SetCurrency(string customerCurrency, string returnUrl) { if (!string.IsNullOrEmpty(customerCurrency)) { var record = _context.Currencies.FirstOrDefault(w => w.DisplayLocale == customerCurrency); if (record != null) { Response.Cookies.Append( "Cella.Locale", record.DisplayLocale, new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential = true } ); } } return LocalRedirect(returnUrl); }
2. 视图渲染前读取Cookie赋值给模型
在返回对应视图的Controller动作中,优先读取Cookie中的货币值覆盖模型默认值:
public IActionResult YourPageAction() { var model = new 你的视图模型类名(); model.AvailableCurrencies = _context.Currencies.ToList(); // 读取已保存的货币配置 if (Request.Cookies.TryGetValue("Cella.Locale", out var savedLocale)) { var matchedCurrency = model.AvailableCurrencies.FirstOrDefault(c => c.DisplayLocale == savedLocale); if (matchedCurrency != null) { model.CurrentCurrencyId = matchedCurrency.Id; model.DisplayLocale = matchedCurrency.DisplayLocale; return View(model); } } // 无保存配置或匹配失败走默认逻辑(英镑) var defaultCurrency = model.AvailableCurrencies.FirstOrDefault(c => c.Name == "英镑") ?? model.AvailableCurrencies.First(); model.CurrentCurrencyId = defaultCurrency.Id; model.DisplayLocale = defaultCurrency.DisplayLocale; return View(model); }
3. 修正Razor视图的选中判断逻辑
统一Select列表项的选中判断标准,与绑定的DisplayLocale对齐:
@if (Model.AvailableCurrencies.Count > 1) { var returnUrl = webHelper.GetRawUrl(Context.Request); var currencies = Model.AvailableCurrencies.Select(x => new SelectListItem { Text = x.Name, Value = x.DisplayLocale, Selected = x.DisplayLocale.Equals(Model.DisplayLocale) }).ToList(); <form id="SetCurrency" asp-controller="Warehouse" asp-action="SetCurrency" asp-route-returnUrl="@returnUrl" method="post" class="form-horizontal nav-link text-dark" role="form"> <select id="customerCurrency" name="customerCurrency" asp-items="@currencies" onchange="this.form.submit();"> </select> </form> }
注:删除了重复的
asp-for属性,避免自动生成的name与手动设置的customerCurrency冲突导致提交失败。
内容的提问来源于stack exchange,提问作者dotnetdevcsharp
相关产品推荐
相关产品推荐

