具有Dictionary< string,string>的下拉列表不适用于所选值 [英] Dropdownlist for with Dictionary<string,string> is not working with selected value

查看:140
本文介绍了具有Dictionary< string,string>的下拉列表不适用于所选值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以这种方式在MVC3中绑定一个下拉列表.

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

型号

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;
}

控制器

ViewBag.SexPreference = MemberHandler.SexPreference();

查看

@{
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.

推荐答案

为什么有模型时要设置ViewBag.SexPreference?忘了这个ViewBag.另外,您应该具有2个属性才能创建下拉列表:标量类型属性用于保存所选值,而collection属性用于保存所选值列表.现在,您似乎只使用一个,并试图将DropDown绑定到显然没有任何意义的collection属性.

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);
}

并在您的视图内:

@model MyViewModel

@Html.DropDownListFor(
    m => m.SelectedSexPreference, 
    new SelectList(Model.SexPreferences, "Value", "Key")
)

这篇关于具有Dictionary&lt; string,string&gt;的下拉列表不适用于所选值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆