Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdownlist for with Dictionary<string,string> is not working with selected value

I am trying to bind a dropdown in MVC3 in this way.

Model

public static Dictionary<string, string> SexPreference()
{
      var dict = new Dictionary<string, string>();
      dict.Add("Straight", "S");
      dict.Add("Gay", "G");
      dict.Add("Bisexual", "BISEX");
      dict.Add("Bicurious", "BICUR");
      return dict;
}

Controller

ViewBag.SexPreference = MemberHandler.SexPreference();

View

@{
var itemsSexPreference = new SelectList(ViewBag.SexPreference, "Value", "Key", Model.sexpreference);
}

@Html.DropDownListFor(m => m.sexpreference, @itemsSexPreference)

Dropdown is not selecting the selected value, don't know why.

like image 482
Jitendra Pancholi Avatar asked Feb 07 '13 06:02

Jitendra Pancholi


2 Answers

Why are you setting ViewBag.SexPreference when you have a model? Forget about this ViewBag. Also you should have 2 properties in order to make a dropdown list: a scalar type property to hold the selected value and a collection property to hold the list of selected values. Right now you seem to be using only one and attempting to bind the DropDown to a collection property which obviously doesn't make any sense.

Do it the right way, by using a view model:

public class MyViewModel
{
    public string SelectedSexPreference { get; set; }
    public Dictionary<string, string> SexPreferences { get; set; }
}

that you would populate in your controller action and pass to the view:

public ActionResult SomeAction()
{
    var model = new MyViewModel();

    // Set the value that you want to be preselected
    model.SelectedSexPreference = "S";

    // bind the available values
    model.SexPreferences = MemberHandler.SexPreference();

    return View(model);
}

and inside your view:

@model MyViewModel

@Html.DropDownListFor(
    m => m.SelectedSexPreference, 
    new SelectList(Model.SexPreferences, "Value", "Key")
)
like image 193
Darin Dimitrov Avatar answered Oct 24 '22 00:10

Darin Dimitrov


Model.sexpreference must be one of these values: Straight... This will Work:

public static Dictionary<string, string> SexPreference()
{
  var dict = new Dictionary<string, string>();
  dict.Add("S", "Straight");
  dict.Add("G", "Gay");
  dict.Add("BISEX", "Bisexual");
  dict.Add("BICUR", "Bicurious");
  return dict;
}

@{
    var itemsSexPreference = new SelectList(ViewBag.SexPreference, "Key", "Value", "S");
}
like image 25
karaxuna Avatar answered Oct 23 '22 23:10

karaxuna