Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST via a link in ASP.NET Core

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);
}
like image 602
serge Avatar asked Sep 11 '17 12:09

serge


People also ask

How do I redirect in net core?

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.

What is Usebrowserlink?

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.

Which ASP NET tag creates a link to another browser page?

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.


1 Answers

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.

like image 152
Chris Pratt Avatar answered Sep 28 '22 03:09

Chris Pratt