i'm writing mvc app in .net core, i have problem with localization, i don't know how to add IViewLocalizer to my grid view. Here is my code:
@using NonFactors.Mvc.Grid;
@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer
@model IEnumerable<WeegreeEmployeeFormsCore.Models.Employee>
@(Html
.Grid(Model)
.Build(columns =>
{
columns.Add(model => model.Name).Titled(Localizer["Name"]).Sortable(true).Filterable(true);
columns.Add(model => model.Surname).Titled(Localizer["Surname"]).Sortable(true).Filterable(true);
columns.Add(model => model.EmploymentDate).Titled(Localizer["Hired"]).Sortable(true).Filterable(true);
columns.Add(model => model.Country).Titled(Localizer["Country"]).Filterable(true).Sortable(true).Filterable(true);
columns.Add(model => model.EmploymentForm).Titled(Localizer["EmploymentForm"]).Filterable(true);
columns.Add(model => $"<a href=\"{Url.Action("Edit", "Form")}/{model.EmployeeId}\">{Localizer["Edit"]}</a>").Encoded(false);
columns.Add(model => $"<a href=\"{Url.Action("Details", "Form")}/{model.EmployeeId}\">Details</a>").Encoded(false);
})
.Pageable(pager =>
{
pager.PagesToDisplay = 10;
pager.CurrentPage = 1;
pager.RowsPerPage = 10;
})
.Sortable()
.Empty("No data found")
)
when i use {}
to insert inside expression model.EmployeeId
it works - link is working, but when i want to use Localizer to get inscription Edit/Edytuj/змінити etc
. instead of i got this in my view :
Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString
That's because
IViewLocalizer["Foo"]
returns aLocalizedHtmlString
instead of a string. So when you include that in a string interpolation expression, it is calling its ToString method. As ToString has not been redefined in that class, the defaultObject.ToString()
implementation returns the type name:Razor knows how to handle LocalizedHtmlString instances when rendering a page, so this renders as expected:
If you want to manually concatenate the localized string, then you need to make sure you get the
LocalizedHtmlString.Value
property:Compare that with your approach without calling
.Value
:I was having a similar problem when trying to pass Localization with multiple values into a partial view. I was able to solve it by using the WriteTo() method.
As the accepted answer can be a bit misleading in regards to interpolation queries.
Internally the
Localizer
finds the text and runs it throughstring.Format
. This enables us to feed it with strings likepseudoText > This text will be {0} by the {1}
.To modify what's in the braces
This will output
This text will be transformed by the lozalizer