将DropDownListFor绑定到字典 [英] Binding DropDownListFor helper to a dictionary

查看:101
本文介绍了将DropDownListFor绑定到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建并填充字典,并希望通过使用 DropDownListFor 辅助方法.

I'm creating and populating a Dictionary and want to bind it to drop down list by using DropDownListFor helper method.

如何将字典的keyvalue映射到下拉菜单?

How do I map that dictionary's key and value to dropdown?

看来我应该可以做类似的事情:

It looks like I should be able to do something like:

@Html.DropDownListFor(o => o.key, o => o.value, MyDictionary);

似乎第一个参数应该是映射键/值对的LINQ语句,第二个参数是字典本身.

It seems like the first parameter should be a LINQ statement that maps key/value pair and second parameter is dictionary itself.

推荐答案

您不能将下拉列表绑定到字典.这没有道理.为了生成一个下拉列表,您需要做两件事:将所选值绑定到的标量属性和将下拉列表的选项绑定的集合.您只有这两件事中的第二个是字典.因此,您不能使用强类型的帮助器.

You cannot bind a dropdown list to a dictionary. It doesn't make sense. In order to generate a dropdown list you need 2 things: a scalar property to bind the selected value to and a collection to bind the options of the dropdown list. You only have the second of those two things which is the dictionary. So you cannot use a strongly typed helper.

您可以做以下丑事:

@Html.DropDownList("SelectedValue", new SelectList(MyDictionary, "Key", "Value"))

但是,当然更好的方法是使用视图模型:

but of course a far better approach would be to use a view model:

public class MyViewModel
{
    public string SelectedValue { get; set; }
    public SelectList Values { get; set; }
}

您将在控制器操作中填充的内容:

which you would populate in your controller action:

public ActionResult Foo()
{
    Dictionary<string, string> dic = ...
    var model = new MyViewModel
    {
        Values = new SelectList(dic, "Key", "Value")
    };
    return View(model);
}

最后进入您的强类型视图:

and finally in your strongly typed view:

@model MyViewModel
@Html.DropDownListFor(x => x.SelectedValue, Model.Values)

这篇关于将DropDownListFor绑定到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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