Question

I have a data source that is handing me an IEnumerable<SelectListItem> The text in each selectListItem is all uppercase. I would like to find the easiest way to change them to proper case without actually changing the datasource.

Was it helpful?

Solution

I think the best answer might be to convert your Enumerable to SelectListItems before passing to your view, and converting the case to TitleCase then. Some faux code for you:

Given this DataSource:

EnumerableItems = new List<string>() { "ITEM ONE", "ITEM TWO" };

I have this on my ViewModel:

public string BoundValue { get; set; }
public IEnumerable<SelectListItem> SelectListItems { get; set; }

I set the SelectListItems like so:

viewModel.SelectListItems = from e in EnumerableItems
                            select new SelectListItem
                            {
                                Selected = e == dto.BoundValue,
                                Text = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(e.ToLower()),
                                Value = e
                            };

In my view something like:

@Html.DropDownList("BoundValue", new SelectList(Model.SelectListItems, "Value", "Text"), "-- select --")

And I get this:

enter image description here

Theoretically I think you could also change the case in the view by calling the ToTileCase where the "Text" argument is, but that would be less clean I think.

EDIT: I amended the code for creating the SelectListItem to have the Value remain uppercase (as e, instead of e.ToTitleCase()) - since I guess it will bind to your original data source ultimately :)

OTHER TIPS

Okay, in an effort to provide a little direction. If you own the class that is each list item you do have an option. Override the ToString() method. Like this maybe:

public override string ToString()
{
    // here is a really primitive algorithm
    return string.Format("{0}{1}",
        this.DisplayProperty.Take(1),
        this.DisplayProperty.Substring(1).ToLower());
}

However, if you don't own the class that is each list item you're pretty stuck because you don't want to modify the data source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top