Romias
Romias

Reputation: 14133

How to internationalize DropDownList items using Razor

We are working on an MVC website where some list have user and system values. So, system items need to be internationalized to display in the user language, and user items are already in the user language.

Those system items have a flag called "IsSystem" to differenciate the ones we need to internationalize. This flag also mean that the user cannot update or delete those items.

Well, we are using @Html.DropDownList to render this DropDownList... so I don't find how to step in the middle of dropdownlist loading logic... in order to place an if statement checking for the IsSystem flag and getting the correct text from resource files.

Thanks for any idea on how to handle this...

EDIT:

Controller code:

ViewBag.idTaskType = new SelectList(db.TaskTypes, "idTaskType", "Name");

where db is Context from EntityFramework

View Code:

@Html.DropDownList("idTaskType", String.Empty)

Upvotes: 0

Views: 1419

Answers (2)

Nawaz
Nawaz

Reputation: 124

I am imagining your "TaskTypes" tables as below

idTaskType  Name
----------  -----
1           Task1
2           Task2
3           Task3

Let us consider two different "App_GlobalResources"

[1]en-US

Name    Value
----    -----
Task1   Create  
Task2   Update
Task3   Delete

[1]sv

Name    Value
----    -----
Task1   Skapa
Task2   Uppdatera
Task3   Ta bort

Now develop a IEnumerable SelectListItem

public IEnumerable<SelectListItem> TaskTypeList { 
        get{
            List<TaskTypes> List = db.TaskTypes.ToList();
            return List.Distinct().OrderBy(x => x.Name).Select(x => new SelectListItem
                    {
                        Value = x.idTaskType.ToString(), 
                        Text = (HttpContext.GetGlobalResourceObject("Task", x.Name)).ToString()
                    });
        } 
    }

Finally use

@Html.DropDownList("idTaskType", new SelectList(Model.TaskTypeList, "Value", "Text"), String.Empty)

Thanks.

Upvotes: 2

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

You would need to have internationalized versions of your data. So, you could do something like this:

ViewBag.idTaskType = new SelectList(db.TaskTypes
   .Where(x => x.language == "en"), "idTaskType", "Name");

Upvotes: 0

Related Questions