Fixing SelectedValue issue on DropbDownListFor with SelectList

Posted by – July 30, 2012

After spent several hours trying to figure out how the SelectedValue works on DropDownListFor, I finally figure out how to do it, you can also check my answer on stackoverflow here.

It’s very simple to get SelectList and SelectedValue working together, even if your property isn’t a simple object like a Int, String or a Double value.

Example:

Assuming our Region object is something like this:

1
2
3
4
public class Region {
     public Guid ID { get; set; }
     public string Name { get; set; }
}


And your view model is something like:

1
2
3
4
5
public class ContactViewModel {
     public DateTime Date { get; set; }
     public Region Region { get; set; }
     public List<Region> Regions { get; set; }
}

You can have the code below:

1
@Html.DropDownListFor(x => x.Region, new SelectList(Model.Regions, "ID", "Name"))

Only if you override the ToString method of Region object to something like:

1
2
3
4
5
6
7
8
9
public class Region {
     public Guid ID { get; set; }
     public string Name { get; set; }

     public override string ToString()
     {
         return ID.ToString();
     }
}

This have 100% garantee to work.

But I really believe the best way to get SelectList 100% working in all circunstances is by using the Equals method to test DropDownList or ListBox property value against each item on items collection.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>