I am creating a SelectList from a List(T) class to use to populate a HtmlHelper.DropDownList in an MVC view, setting the dataValueField and dataTextField in the Select List constructor. The text that should be displayed doesn't excatly match one of the properties on my class and still needs to be manipulated. Is there any way of doing this through the SelectList constructor? I realise I could do this by creating a struct or class to use as the IEnumerable input for the Select list but I'd prefer not if I don't need to.
My Controller code is currently:
var members = MemberService.GetAll();
this.ViewData["Members"] = new SelectList(members, "Id", "Name");
My View code is currently:
<%= Html.DropDownList("Members") %>
Instead of "Surname" as my display field I'd like to be able to preformat the field by combining (and formatting) two properties.
For those that use LINQ. Instead of:
you can use:
and then use ViewBag.MemberList in your Razor code like
You can create an extension method and set whatever you want as the text. It could be something as
Then you call this method as:
You can create loop through the members list, adding the values to a new list that you then create the SelectList from. Something like:
I can't remember if you can use an anonymous type like that or not, but if not you can create an small data class to use as an intermediary.