kkakkurt
kkakkurt

Reputation: 2800

Dynamic model binding in ASP.NET MVC Razor for multilanguage

I want to use multilanguage structure in my ASP.NET MVC project. I have only two languages. So I keep two string fields in my DB for two languages (Eg: Header_EN and Header_TR).

I get my current language value from my .resx file dynamically (Eg: EN or TR). But I have to use a dynamic model in my view. Normally I'm using this for single language:

    @model MyProject.Models.tTextTable

    <div class="TextDetailContainer">
        @Html.Raw(Model.MyTextDetail_EN)
    </div>

And I want to use a dynamic model value for multilanguage something like that:

    @model MyProject.Models.tTextTable

    <div class="TextDetailContainer">
        @Html.Raw(Model.("MyTextDetail_" + Resources.Language.CurrentLanguage))
    </div>

Is there a possible way to do this with this logic or is there another way to create dynamic model in Razor?

Upvotes: 0

Views: 1818

Answers (1)

Dmitri Trofimov
Dmitri Trofimov

Reputation: 763

If your model is dynamic then you can cast it to IDictionary<string, object> and get the value from it:

var dictionary = (IDictionary<string, object>)model;
var text = dictionary ["MyTextDetail_" + Resources.Language.CurrentLanguage] as string;

Although you should probably have one property MyTextDetail and set it in controller to appropriate localized value.

Upvotes: 2

Related Questions