Reputation: 124
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
Upvotes: 0
Views: 3792
Reputation: 512
Yes, Steve is right. Your task is completely about using resources. You shouldn't place description fields for every culture in your model. It is completely wrong. You can find more about ASP.NET MVC app internationalization there: http://afana.me/post/aspnet-mvc-internationalization.aspx.
Upvotes: 0
Reputation: 633
Resources! Specifically localized resources. You can have the file names in resources, or have the files themselves stored in resources and access them through the resource manager.
The resource manager will resolve the current culture for a particular value and default to a base language if the localized resource does not exist.
This is pretty old school functionality, but it still works and .Net provides facilities to automagically resolve the resources. Also localized resources are the way applications have been internationalized for at least three decades.
Upvotes: 0
Reputation: 2029
The problem is with DisplayNameFor which do not accept an expression that executed a method as parameter. It will work if you get rid of it and use just @Model.GetPropertyValue("Description_" + @culture)
Upvotes: 2