Razor Html.DisplayFor()没有选择正确的本地化资源

时间:2018-05-03 04:55:42

标签: c# asp.net-mvc razor resx

Razor根据当前的线程文化没有返回本地化资源,我不明白为什么。它总是在中性resx文件中返回字符串。

PurchaseOrderModel.cs:

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

在同一个文件夹中,我有:

PurchaseOrderModelRes.resx - >中立资源。访问修饰符设置为“公共”。 PurchaseOrderModelRes.fr.resx - >本地化的法国资源。

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();

1 个答案:

答案 0 :(得分:0)

通过在ResourceFilter中设置文化而不是控制器操作来解决此问题,如此线程所建议的那样:ASP.NET MVC (Async) CurrentCulture is not shared between Controller and View

现在,文化在控制器和视图之间正确共享。