0

Razor does not return the localized resource according to the current thread culture and I have no idea why. It always return the string within the neutral resx file.

PurchaseOrderModel.cs:

public class PurchaseOrderModel : ProfileSpecificEntityModel {
    [Display(ResourceType = typeof(PurchaseOrderModelRes), Name = "ExpectedDeliveryOn")]
    public DateTimeOffset? ExpectedDeliveryOn { get; set; }
}

In the same folder, I have:

PurchaseOrderModelRes.resx -> Neutral resource. Access modifier set to "public". PurchaseOrderModelRes.fr.resx -> Localized French resource.

PurchaseOrderReport.cs:

<div>@Html.DisplayNameFor(purchaseOrder => purchaseOrder.ExpectedDeliveryOn)</div>

PurchaseOrderController.cs:

[HttpGet]
public async Task<IActionResult> PurchaseOrdersReportAsync([FromQuery] PurchaseOrderListQueryOptionsModel queryOptions) {
    CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("fr"); //Should use *.fr.resx files.
    CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo("fr");
    PaginatedList<PurchaseOrder> purchaseOrders = await _purchaseOrderService.GetPurchaseOrdersAsync(CurrentUser, queryOptions.ToQueryOptions());
    PaginatedListModel<PurchaseOrderModel> purchaseOrderModels = _paginatedListModelConverter.Convert(purchaseOrders, p => _purchaseOrderModelConverter.Convert(p));
    return View("PurchaseOrderReport", purchaseOrderModels.Items);
}

Startup.cs:

services.AddMvc().
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
olivierr91
  • 1,243
  • 3
  • 13
  • 29
  • It may be a problem with `async`, and depending on your .Net version, this question may help https://stackoverflow.com/questions/30662668/keep-currentculture-in-async-await – devio May 03 '18 at 06:17
  • Indeed it was. To keep the method async I had to set the culture info in a resource filter. Thanks – olivierr91 May 04 '18 at 15:34

1 Answers1

0

Solved the issue by setting the culture in a ResourceFilter instead of the controller action, as proposed by this thread: ASP.NET MVC (Async) CurrentCulture is not shared between Controller and View

Now the culture is shared between the controller and the view correctly.

olivierr91
  • 1,243
  • 3
  • 13
  • 29