Friday, May 6, 2011

IDictionary to SelectList ?

I have an IDictionary, now I want to use these values in a selectlist. How do I do this?


From stackoverflow
  • Well, IDictionary inherits from IEnumerable so you ought to be able to pass that dictionary to one of the constructors for SelectList.

    Meta-Knight : You should pass the Values property instead of just the IDictionary though. If you just pass the IDictionary you will get key/value pairs instead of the values.
    Andrew Hare : Please post the code you are using so that we can use that to test.
  • Just set the Value and Key for dataValueField and dataTextField. You can either do this in your View itself or from your action (havent tested the code below).

    var targets = new Dictionary<string, string>();
    targets.Add("Blank", "_blank");
    targets.Add("Parent", "_parent");
    targets.Add("Self", "_self");
    targets.Add("Top", "_top");
    ViewData["MyList"] = new SelectList(targets, "Key", "Value");
    Tony Borf : Got it, Thanks for the help.


Post a Comment