Home > Mobile >  ASP.NET Core - change form action to list options in view
ASP.NET Core - change form action to list options in view

Time:11-28

I have controller for changing website language, saving cookie and returning url.

`

using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;

namespace Website.Controllers;
public class CultureController : Controller
{
    [HttpPost]
    public IActionResult SetCulture(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
            new CookieOptions { Expires = DateTimeOffset.UtcNow.AddDays(365) }
        );
        
        return LocalRedirect(returnUrl);
    }
}

`

And in View I need create html list for better user experience but I don't understand how to change from 'form' to 'list' or how to submit changes and return url `

@using Microsoft.AspNetCore.Localization
@using Microsoft.Extensions.Options

@inject IOptions<RequestLocalizationOptions> LocalizationOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();

    var cultureItems = LocalizationOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.EnglishName })
        .ToList();

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

<!-- FROM FORM -->
<div >
    <form asp-controller="Culture" asp-action="SetCulture" asp-route-returnUrl="@returnUrl" >
        <select name="culture"
                onchange="this.form.submit();"
                asp-for="@requestCulture.RequestCulture.UICulture.Name"
                asp-items="cultureItems">
        </select>
    </form>
</div>

<!-- TO LIST -->

<div >
    <a href="#" ><i ></i></a>
        <ul >
        @foreach (var item in LocalizationOptions.Value.SupportedUICultures)
        {
            <li><a href="#?HOW">@item.Name.ToUpper()</a></li>
        }
    </ul>
</div>

`

I tried with anchor tag helper but without success

output enter image description here

The Result:

enter image description here

It just performed as the document,and if you tried with mulipule providers,you could try to change request culture providers order which has been mentioned in the document

  • Related