mvc

[MVC] SelectList combining multiple columns in text field

[MVC] SelectList combining multiple columns in text field,constructor overloads
Share it:

The SelectList class provides an easy way to build a list of options for a dropdown or select list. Two of the constructor overloads allow you to provide a list of objects and specify which property to use from the value (data value field) and text (data text field) of the dropdown or select list. But what happens when you want the text (or value) to be two or more other properties combined?

A quick search of the web reveals two really horrible and yet common solutions. In the first, you build the SelectList by using for each to loop through your original data. The second is even worse as you build another list of objects containing just value and text properties that you pass to SelectList. There are three main reasons why I hate these solutions:
  • hey make your controller actions longer than they need to be
  • How something is displayed is business logic and not controller logic
  • It usually results in a lot of copy and pastes making it harder to change later
Luckily there is a much easier and cleaner way to do this. All you need to do is add a new property with a getter method that returns the combined value. You can even add formatting like brackets around an ID or commas in a name. Below is an example where FullName is the FirstName and LastName combined.


public Contact
{
    public int ID { get; set; }
 
    public string FirstName { get; set; }
 
    public string LastName { get; set; }
 
    public string FullName
    {
        get
        {
            return LastName + ", " + FirstName;
        }
    }
}

Now when you call SelectList you simply use “FullName” as the name of the property for the text value.



SelectList list = new SelectList(contacts, "ID", "FullName");

This is a win on three fronts:
  • The solutions are much cleaner.
  • It results in less copy and pastes code.
  • If want to change the format later you only need to make the change in one place (the model) rather than every controller or view that uses it
Share it:

mvc

Post A Comment:

0 comments: