I try to POST to the SetLanguage action via a link, but not sure how to finalize the following code:
<form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" role="form">
@foreach (var culture in cultures) {
<div>
<a href="[email protected]">@culture.Name</a>
</div>
}
</form>
Should I use the form
or there is a direct method to send a POST with culture : 'EN'
param, by eg?
Does the @Url.Action(action: "SetLanguage", controller:"Home", values: new { culture = culture.Name }, protocol:"POST")
do the work ?
My Controller code is
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
Links are GET requests. You cannot post via a link; that is what forms are for. You'd need something like:
<form id="selectLanguage" asp-controller="Home" asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path" method="post" role="form">
@foreach (var culture in cultures) {
<div>
<button type="submit" name="culture" value="@culture.Name">
@culture.Name
</button>
</div>
}
</form>
Then, whichever button you click, its value will be posted. If you want it to look like links, you can style the buttons accordingly.
Alternatively, you can keep the links, but you would need to use AJAX to post on click.