Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

razor - MVC4 localization. Accessing resx from view

In my view I would like to access resource strings from the specific local resource on that file.. Just as you know it from web-forms:

(string)GetLocalResource("Title");

Painless and smooth. The framework handles which .resx file to get from the culture info code extension (.en-EN.resx).

Is that possible in MVC4 with Razore view? And how?

Iv'e noticed that i can set the Custom Tool property on the .resx file to PublicResXFileCodeGenerator. That way I can access it from the view. Example: I've created 2 resource files for index.cshtml in danish and english. Just as I would in web-forms. Here's what I wish i could write (Custom Tool Name property set to 'ViewResource'):

@ViewResource.Title

Bam. If current culture is danish, title will be "Forside", and if english it would be "Home". But instead the only options I am given is choosing a specific file. And from that choose the desired string:

@ViewResource.Index_cshtml_en-EN_resx.Title

Thats not dynamic. So I thought I could make an extension class that would replace the en-EN/da-DK somehow. But that really seems like relatively alot of work for something so "simple" and already well and easy intergrated into web-forms. There has to be another way. Surely the mvc team has some smart mechanism for us like everything else :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I used the special .NET folder App_LocalResources.

Here are the steps

Add the .resx files to that folder (i.e.: Resource.resx, Resource.es-ES.resx)

Right click on each .resx file and select properties and make sure the following are selected

Build Action: Embedded Resource 
Custom Tool: PublicResXFileCodeGenerator
Custom Tool Namespace: Resources

Then in your view you can use the Resources name space to access the text in your .resx file

<h2>@Resources.Resource.Global_Title<h2>

@Resources because that is the name that you gave in the Custom Tool Namespace and .Resource because that is the name of the .resx file

Also make sure that the resources are set to Public

To access the resources from any model just add a single line

using Resources;  //<<-- This line

namespace Concordia_CRM.Models
{
    public class SolicitudDemo
    {
        [Required]
        [Display(Name = "SD_NombreEmpresa", ResourceType = typeof(Resource))]
        public string NombreEmpresa { get; set; }

...
}

More details can be found on this post.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...