Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Localization View: IViewLocalizer inside Linq expression

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

like image 700
tuchy Avatar asked Feb 07 '23 00:02

tuchy


1 Answers

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>
like image 119
Daniel J.G. Avatar answered Feb 08 '23 14:02

Daniel J.G.