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 a LocalizedHtmlString
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 default Object.ToString()
implementation returns the type name:
var foo = Localizer["Foo"].ToString();
//foo gets assigned "Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString"
Razor knows how to handle LocalizedHtmlString instances when rendering a page, so this renders as expected:
<p>Hello @Localizer["World"]</p>
//renders <p>Hello World</p>
If you want to manually concatenate the localized string, then you need to make sure you get the LocalizedHtmlString.Value
property:
@{
var text = $"Hello {Localizer["World"].Value}";
}
<p>@text</p>
//renders <p>Hello World</p>
Compare that with your approach without calling .Value
:
@{
var text = $"Hello {Localizer["World"]}";
}
<p>@text</p>
//renders <p>Hello Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString</p>
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