2

I have a 'webshop' where you can buy all sorts of fruits, vedgetables and more. this website can be used in multiple languages. when the user is looking for a specific item he's using a variable to filter through the items. the url will look like this localhost/Products?item=AARB.

If the user changes languages it will return the returnUrl. the returnUrl only returns the action method looking like localhost/Products. I want it so that the returnUrl also contains the query parameter as it is a lot more use friendly to go back to your searched item when changing languages.

My ProductsController has the following Index Method:

[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");
                
    }

The querystring item is the users input. for example: He wants to look for banana's(BANA) or Oranges(MAND). when the user changes the language of the website, this querystring needs to be sent back as well, returning a full url of localhost/Products?item=BANA from, what I assume is my HomeController

In my HomeController I have made a method that changes the CultureInfo for the user.

[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);
}

Hopefully I've made my intentions and code clear enough to help find a solution to my problem :)

Edit I forgot to post my PartialView to show where I send my returnUrl back to the 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>

2 Answers2

2

You can add the value of the query string to the end of the path.

Here is the modified code:

var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~" 
    : $"~{Context.Request.Path.Value+ Context.Request.QueryString.Value}";

enter image description here

Yihui Sun
  • 755
  • 3
  • 5
0

in your View you have a Codepart where you define the returnUrl you then proceed to give this to your HomeController where you set the language.

you can useContext.Request.Path to also find the value of your querystring.

//Checks if the path is empty. If not, check the value of your QueryString
var parameters = string.IsNullOrEmpty(Context.Request.Path) ? "" : $"{Context.Request.QueryString.Value }";

    <a asp-action="SetLanguage" asp-route-returnUrl="@returnUrl" asp-route-parameters="@parameters" asp-route-culture="nl-NL" asp-controller="Home">
        <img src="~/css/Languages/nl.png" />

You can create a Variable Parameters and do the same thing you did with your returnUrl. Then in your HomeController you can use both your returnUrl and Parameters.

[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) });
            
            //If parameters is null, only return returnUrl, else return both
            if (parameters != null)
            {
                var item = returnUrl + parameters;
                return LocalRedirect(item);
            }
            else { var item = returnUrl;
                return LocalRedirect(item);
            }
    Console.WriteLine("The new CultureInfo is now: " + CultureInfo.CurrentCulture);
    return LocalRedirect(returnUrl);
}

this reference helped me understand how to use the Context.Request.Path combined with looking at my own code.