asp.net MVC-在DropDownListFor中使用字符串列表 [英] asp.net MVC - using list of strings in a DropDownListFor

查看:47
本文介绍了asp.net MVC-在DropDownListFor中使用字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Html.DropDownListFor与ViewBag中的字符串列表一起使用.

I am trying to use Html.DropDownListFor with the list of strings from a ViewBag.

基本上,我得到了一个ViewBag,其中包含诸如"Adam","Tom","Mike"等之类的字符串列表.

Basically I got a ViewBag with a list of string like "Adam","Tom","Mike" etc...

我在徘徊,是否有可能将此列表传递给DropDownListFor,其中Value和text都是列表中的项.

I was wandering if it is possible to pass this list in to DropDownListFor where both Value and text are the items from my list.

我无法在此处使用foreach ...

I wasn't able to use foreach here...

带有硬编码的示例:

@Html.DropDownListFor(model => model.Name, new SelectList(
          new List<Object>{

               new { value = "Adam" , text = "Adam"  },
               new { value = "Tom" , text = "Tom"  },
               new { value = "Mike" , text = "Mike"  },
               new { value = "Jake" , text = "Jake"  },
            },
          "value",
          "text",
           2))

推荐答案

您可以从字符串列表中生成 SelectListItem 的集合,并将其与 DropDownListFor 帮助器一起使用方法.

You can generate a collection of SelectListItems from the list of strings and use that with DropDownListFor helper method.

var names = new List<string> {"Adam", "Sam"};
ViewBag.Names = names.Select(f => new SelectListItem() {Value = f, Text = f});

并在视图中

@Html.DropDownListFor(f=>f.Name, ViewBag.Names as IEnumerable<SelectListItem>, 
                                                                    "select one")

这篇关于asp.net MVC-在DropDownListFor中使用字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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