使用Dictionary <string,string>的下拉列表不适用于所选值

Jit*_*oli 9 asp.net-mvc asp.net-mvc-3

我试图以这种方式绑定MVC3中的下拉列表.

模型

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;
}
Run Code Online (Sandbox Code Playgroud)

调节器

ViewBag.SexPreference = MemberHandler.SexPreference();
Run Code Online (Sandbox Code Playgroud)

视图

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

@Html.DropDownListFor(m => m.sexpreference, @itemsSexPreference)
Run Code Online (Sandbox Code Playgroud)

下拉列表没有选择所选值,不知道为什么.

Dar*_*rov 23

ViewBag.SexPreference你有模特时为什么要设置?忘了这个ViewBag.此外,您还应该有2个属性才能生成下拉列表:标量类型属性用于保存选定值,集合属性用于保存选定值列表.现在你似乎只使用一个并尝试将DropDown绑定到一个集合属性,这显然没有任何意义.

通过使用视图模型以正确的方式执行:

public class MyViewModel
{
    public string SelectedSexPreference { get; set; }
    public Dictionary<string, string> SexPreferences { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您将在控制器操作中填充并传递给视图:

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);
}
Run Code Online (Sandbox Code Playgroud)

在你的视图中:

@model MyViewModel

@Html.DropDownListFor(
    m => m.SelectedSexPreference, 
    new SelectList(Model.SexPreferences, "Value", "Key")
)
Run Code Online (Sandbox Code Playgroud)


kar*_*una 1

Model.sexpreference 必须是以下值之一: Straight... 这将起作用:

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");
}
Run Code Online (Sandbox Code Playgroud)