【发布时间】:2021-06-10 09:02:13
【问题描述】:
我有一个“网上商店”,您可以在其中购买各种水果、蔬菜等。本网站可以使用多种语言。
当用户正在寻找一个特定的项目时,他正在使用一个变量来过滤这些项目。网址看起来像这样localhost/Products?item=AARB。
如果用户更改语言,它将返回returnUrl。 returnUrl 只返回类似于localhost/Products 的操作方法。我想要它,以便 returnUrl 还包含查询参数,因为在更改语言时返回到您的搜索项目更加友好。
我的 ProductsController 有以下索引方法:
[HttpGet]
public ActionResult Index(string item = "APPE", int amount = 0)
{
var CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
ViewData["amount"] = amount;
//Uses the Logged in Username to match the items related to it's RelatieNummer
var LoggedUser = Convert.ToInt32(User.Identity.Name);
UserCheck ApplicationUser = _context.ApplicationUser.Where(x => x.CompanyNumber == LoggedUser).First();
var itemCheck = item != null ? item.ToUpper() : "";
try
{
var currentCat = _context.Categories.Where(x => x.CategoryCode.Contains(itemCheck)).First();
ViewData["Main_Items"] = FillMainItems(); //This is a different Method which fills Commodity names
var SearchItem = _context.ZzProducts
.Where(x => x.RelatieNummer == LoggedUser)
.Where(x => x.HoofdSoortCode.Contains(itemCheck));
return View(SearchItem);
catch (Exception ex)
{
ModelState.AddModelError("Error", ex.Message);
return View("Error");
}
查询字符串item 是用户输入。例如:他想寻找香蕉(BANA)或橙子(MAND)。当用户更改网站的语言时,这个查询字符串也需要发回,返回一个完整的 url localhost/Products?item=BANA from,我假设是我的 HomeController
在我的 HomeController 中,我创建了一个为用户更改 CultureInfo 的方法。
[HttpGet]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
Console.WriteLine("The new CultureInfo is now: " + CultureInfo.CurrentCulture);
return LocalRedirect(returnUrl);
}
希望我的意图和代码足够清晰,可以帮助我找到解决问题的方法 :)
编辑 我忘记发布我的 PartialView 以显示我将 returnUrl 发送回 HomeController 的位置
@{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~" : $"~{Context.Request.Path.Value}";
}
//Clickable Flags for CultureInfo
<div id="SelectLanguage" title="@Localizer["Language"]">
<a asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" asp-route-culture="nl-NL" asp-controller="Home">
<img src="~/css/Languages/nl.png" />
</a>
<a asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" asp-route-culture="en-US" asp-controller="Home">
<img src="~/css/Languages/en.png" />
</a>
<a asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" asp-route-culture="de-DE" asp-controller="Home">
<img src="~/css/Languages/de.png" />
</a>
<a asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" asp-route-culture="da-DK" asp-controller="Home">
<img src="~/css/Languages/dk.png" />
</a>
</div>
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-core