Current Scenario:

  • I have a model class wich has Descriptions in diferent languages, like Description_en , Description_sp , Description_fr .

  • When a user selects his current language, I have a cookie 'culture' with that value.

***** The objective is to call a different Description, when a different language is selected. If user selects fr, Description_fr should be called, and so on...

My code:

In ModelClass I have a reflection (has seen here: How to call a property of an object with a variable in C# e.g. customer.&fieldName ):

public class Something
    {
        public string Description_en { get; set; } 
        public string Description_sp { get; set; } 
        public string Description_fr { get; set; } 

        //Reflection, makes it possible to select a property to call with a variable
            public string GetPropertyValue(string fieldName)
            {
                PropertyInfo prop = typeof(Something).GetProperty(fieldName);
                return prop.GetValue(this, null).ToString();
            }
    }

In a razor Template I have:

@model IEnumerable<baseTemplate.Models.Something>

<table class="table">
    <tr>
        <th data-lang=@culture>
        <!-- @culture is defined in current scope -->
            @Html.DisplayNameFor(model => model.GetPropertyValue("Description_" + @culture)) 
        </th>
    </tr>
</table>

When it runs to the property GetPropertyValue("...") the following error is displayed:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

My question is: Is there is a way to do this?

P.S. The obvious (and correct) possibility of...

if(@culture == "en"){@Html.DisplayNameFor(model => model.Description_en") }

... Shouldn't be an answer because it would create a 'Hell' of code to maintain afterwards :)

Thank you for the possible help

Related posts

Recent Viewed