Search code examples
c#asp.net-mvcresx

Showing variable text in MVC View


I'm looking for a good solution for the following problem:

I have a ASP.NET MVC Webapplication, used by several of my Clients. Within the application, a client can login, view several pages with information and fill in several forms. This all works great.

What I want however, is to show different texts in the view, depending on a property of the Client (A type in this case). These texts can be multi-lingual, the user can change the language in the application.

I've come up with several solutions for this, but I'm not sure what the best idea is. These are my ideas so far:

Saving info in database

In this case, I would create a table (e.g. 'ProgramTexts'), with a Key, the type of the client, the language and the text it self. In my Controller, I would then retrieve the Keys used in that view, set them in a ViewModel and pass that viewmodel to the view. In the view I can then easily show the value of the given variable in the ViewModel.

I think this will work great for a small sites, but seems a bit chunky with many different controllers and views. I'd rather 'call' the text directly from the view, but making a database call from the view isn't much better.

Resource files

My other idea would be using Resource Files, because of the build in Localization feature. I'm not sure however how to retrieve a variable from a resource, based on a extra variable (the type in this case).

Does anyone have another idea about how to achieve this?


Solution

  • I would go for the resource file option. Is it possible to have different resource files for the types? Or is it possible to have different variable names for the different types?

    eg

    Message1_TypeA
    Message2_TypeB
    

    etc

    Then you could use some clever tricks to read the correct message depending on type, a clever trick such as reflection perhaps.

    Another option might be to delimit the string thus

    Message1 = "A|B|C|D";

    This way you retrieve the message for all types and then in your code you can retrieve the correct message for the current type. Did I explain that well? I don't think I did.