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
516 views
in Technique[技术] by (71.8m points)

.net - How does the App_LocalResources work with MVC?

I've been working through my first MVC application, and I'd like to localize it. I know how to use the App_GlobalResources but I'd prefer to use the App_LocalResources.

In a typical WebForms application, you put the App_LocalResources folder in the same directory as the ASPX file... is this the same in MVC (IE: do I put them in the respective subfolders in the "views" directory)?

Also, when accessing the App_GlobalResources in your view you can do it like so <%=Html.Encode(Resources.Index.Title)%> however I cannot do that with the App_LocalResources. I don't want to have to make my <label runat="server" in order to take advantage of the meta:resourcekey


EDIT:

I discovered ONE method to do this, but I'm not sure if this is the best method. Here's the idea

  1. You put the App_LocalResources folder as a sub folder within your respective View folder
  2. You create resx files that correspond to your Views... IE: Index.resx or About.resx
  3. You set the Resx files properties to be "Public" (PublicResXFileCodeGenerator), "Embeded Resource", "Views.[viewname]" namespace
  4. Create a new resource name called "Title" and put whatever you want in the Value.

Now I can reference the Local Resources using something like this

<%= MyProj.Views.Home.Index.Title%>

The only problem I see with this is the fact that the resources are embedded and I cannot add new locales without re-compiling the project.

Here is my reference on this method.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You should not use App_GlobalResources or App_LocalResources with MVC. That is because of the way these resources work. These resources are not embedded in your project, but are instead compiled by the ASP.NET runtime. This means that your resources will not be available when not running inside the ASP.NET runtime, which means you would lose the ability to unit test your views and controllers if you use resources in them.

This post gives more details about it.

Instead, you should use the approach you mention yourself in your question. Put your resource whereever you want, and set it to 'Embedded resource' and the custom tool should be 'PublicResXFileCodeGenerator'.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...