Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewLocalizer does not return String

Tags:

asp.net-core

On ASP.NET Core 2.0 I have the following:

@ViewData.Title("my title");

Title is a ViewData extension which adds "my title" to ViewData with key Title.

This is working but I need to localize the title so I did the following:

@inject IViewLocalizer Localizer

@ViewData.Title(Localizer["my title"]);

But I get the following error:

Cannot convert from 'Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString' to 'string'

Isn't it strange that I need to call ToString? What am I missing?

like image 580
Miguel Moura Avatar asked Apr 20 '26 16:04

Miguel Moura


1 Answers

You should be calling the Value property instead...

Localizer["my title"].Value

This is because Localizer["foo"] returns a LocalizedHtmlString type.

LocalizedHtmlString class

public class LocalizedHtmlString : Microsoft.AspNetCore.Html.IHtmlContent

This class does not have a converter to string built-in. In addition, I am wondering why you stated that ToString() is working for you. I would think it should return Microsoft.AspNetCore.Mvc.Localization.LocalizedHtmlString rather than the correct value.

like image 116
Svek Avatar answered Apr 25 '26 11:04

Svek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!