c# - ASP.NET MVC6 localizable DisplayAttribute -
i wonder if there possibility use ihtmllocalizer
asp.net mvc6 directly poco classes? have few viewmodels uses displayattribute
in order display translated string in views , validator, requires create additional static class each static property defined (unfortunately static indexers not possible in c#). there better way done?
my current code:
[display(name = "trackingdevice", resourcetype = typeof(testresource))] public string trackingdevice { get; set; } public class testresource { public static string trackingdevice { { //here call ihtmllocalizer via iservicelocator return "field name"; } } }
i have struggled bit , succeeded in compiling working solution question. @szymon sasin answer, although not working against latest version , configuration partial, helped me build solution.
first, configure localization @ startup.cs:
public class startup { public void configureservices(iservicecollection services) { //... services.addlocalization(options => options.resourcespath = "resources"); services .addmvc(mvcoptions => { iserviceprovider provider = services.buildserviceprovider(); istringlocalizer localizer = provider.getservice<istringlocalizer<displayresources>>(); mvcoptions.modelmetadatadetailsproviders.add(new displayattributelocalizationprovider(localizer)); }); //... } }
second, verify folder structure against configured resourcepath. important thing here path custom resource type , path resx files should relative. example:
<root_proj_dir>/resources/resources_common/displayresources.en.resx <root_proj_dir>/resources/resources_common/displayresources.bg.resx <root_proj_dir>/resources_common/displayresources.cs
third, define custom metadata provider:
public sealed class displayattributelocalizationprovider : idisplaymetadataprovider { private istringlocalizer _localizer; public displayattributelocalizationprovider(istringlocalizer localizer) { _localizer = localizer; } public void createdisplaymetadata(displaymetadataprovidercontext context) { context.propertyattributes? .where(attribute => attribute displayattribute) .cast<displayattribute>().tolist().foreach(display => { display.name = _localizer[display.name].value; }); } }
fourth, use in view model this:
public class someviewmodel { [display(name = "email")] public string email { get; set; } }
the "email" value key look-up in displayresources.xx.resx files.
hope many others find info helpful!
Comments
Post a Comment