Jedo
Jedo

Reputation: 1

Dynamically specify a property on a model using razor view engine

I have a razor view with model object that is a collection of items that have two language properties, one for English and one for French. I am looking for a way to dynamically reference the correct language property in a razor view.

I can do this:

if (Culture == "en-CA")
    return model.English;
else
    return model.French;

But I want to do something like this:

if (Culture == "en-CA")
    lang = "English"
else
    lang = "French"

...

@foreach (var record in Model) {
    @record.lang
}

Any ideas?

Upvotes: 0

Views: 105

Answers (1)

Jess Chadwick
Jess Chadwick

Reputation: 2373

Razor syntax just gives you an easy way to write C# or VB.NET in your views... but you are still using static language. To answer your question with a question: how would you accomplish the same thing outside of Razor? e.g. what code would you write in order to render the same thing to the console?

I don't know what your classes actually look like, but if you say they are dictionaries then you could just do:

@foreach(var in record in Model) {
    @record[lang]
}

just like any normal dictionary.

Upvotes: 1

Related Questions