Reputation: 905
I can't find any examples on how to localize text within a C# asp.net.core application. I would appreciate any help.
I'm assuming that I need to use StringLocalizaer somehow.
Thanks
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
//using Microsoft.Extensions.Localization;
namespace NotificationSystem.Models
{
public class GroupList : List<Group>
{
public GroupList()
{
LoadGroupTypes();
}
protected List<Group> _Groups { get; set; }
public List<SelectListItem> GroupTypes { get; set; }
public List<SelectListItem> LoadGroupTypes()
{
// ToDo: Implement other GroupTypes / DB Settings pull
GroupTypes = new List<SelectListItem>
{
new SelectListItem
{
Text = "USER-STATIC",
Value = "Users List - Static" // ToDo: Globalize
}
};
return GroupTypes;
}
}
}
Upvotes: 1
Views: 2418
Reputation: 5729
One way is to localize these values in the view, just like any other text localization:
@inject IStringLocalizer _localizer;
<select ..>
@foreach(var item in Model.GroupList)
{
<option value="@_localizer[item.Value]">@_localizer[item.Text]</option>
}
</select>
Another way is to instantiate the model with IStringLocalizer
in constructor:
public class GroupList : List<Group>
{
private readonly IStringLocaizer _localizer;
public GroupList(IStringLocalizer localizer)
{
_localizer = localizer;
LoadGroupTypes();
}
// ...
public List<SelectListItem> LoadGroupTypes()
{
// ToDo: Implement other GroupTypes / DB Settings pull
GroupTypes = new List<SelectListItem>
{
new SelectListItem
{
Text = _localizer["USER-STATIC"],
Value = _localizer["Users List - Static"] // ToDo: Globalize
}
};
return GroupTypes;
}
}
Then you have to pass an instance of IStringLocalizer
while creating the model:
public HomeController : Controller
{
private readonly IStringLocalizer _localizer;
public HomeController(IStringLocalizer localizer)
{
_localizer = localizer;
}
public IActionResult Index()
{
// ...
var groupList = new GroupList(_localizer);
}
}
Upvotes: 1
Reputation: 186
You correctly think that it is necessary to use
Microsoft.Extensions.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
namespace Localization.Controllers
{
[Route("api/[controller]")]
public class AboutController : Controller
{
private readonly IStringLocalizer<AboutController> _localizer;
public AboutController(IStringLocalizer<AboutController> localizer) // use dependency injector
{
_localizer = localizer;
}
[HttpGet]
public string Get()
{
return _localizer["About Title"];
}
}
}
You can use this code before writing the key-value to the resource file
All information is here
Add dictonary in resource is here
Upvotes: 1