简体   繁体   中英

Best way to use C#-Ressources (ResX Files) in Typescript?

our current project is in ASP.Net MVC with Razor. We use ResX Files for a few thousend translations. In C# and Asp.net Razor this is pretty easy with HTML:

<div>@Ressources.Local.Test</div>

Now when I wrote JavaScript I normaly did this within the cshtml files with razor like this:

<script>alert('@Ressources.Local.Test');</script>

Which works but seems a bit ugly...

A few weeks ago we starded with Typescript, and, of course excluding (nearly) all javascript code to ts-files.

The only solution we found here, to get the ressources from C# to Typescript is through a "hack":

We made a ressources.cshtml file in which we just include javascript variables:

var ressourceTest = "@Ressource.Local.Test";

We load this ressource.cshtml at first in our _layout.cshtml. Additional, we have a self need a selfmade declarion for this variable to jump from javascript to typescript in our projectDeclarions.d.ts:

var ressourceTest:string;

And now we can use the ressource in our typescript file test.ts:

alert(ressourceTest);

As you can see it is a working "hack" or "workaround" but it seems to likly kill us for a few thousend ressources... It's handmade, the maintain duration and work is high...

Any better ideas?

I have seen a few good ideas around this.

You could supply an JSON endpoint in your MVC application to give you chunks of translations. You would decide how granular you want to make it, but you would essentially JSON serialize a translation, or set of translations and send it back. This would avoid stuffing a big view with hundreds of the things.

Another alternative is to place translations in the view to make them available, but contextually. So if you had a button that you are using to trigger some AJAX call to the server and you need to say "Update Worked" or "Update Failed" you could put the attributes inline...

<button ... data-msg-success="Saved OK" data-msg-failed="A problem occurred" />

And you could populate these attributes with your resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM