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);
}
Use RedirectResult in ASP.NET Core MVC You can use any of the following methods to return a RedirectResult: Redirect – Http Status Code 302 Found (temporarily moved to the URL provided in the location header) RedirectPermanent – Http Status Code 301 Moved Permanently.
It creates a communication channel between the development environment and one or more web browsers. Use Browser Link to: Refresh your web app in several browsers at once.
Use the HyperLink control to create a link to another Web page. The HyperLink control is typically displayed as text specified by the Text property. It can also be displayed as an image specified by the ImageUrl property. If both the Text and ImageUrl properties are set, the ImageUrl property takes precedence.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With