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.
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")
)
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With