我试图将下拉列表转换为html helper.dropdownfor()

时间:2014-04-10 05:46:52

标签: c# asp.net asp.net-mvc

我的下拉代码目前在下面,我知道我需要的是这种格式:

IEnumerable<SelectListItem> selectlist

我目前正在使用的是此代码,我需要将其转换为具有以下信息的ienumerable selectlistitem

<select id="paperStyle" name="paperStyleList">
        <option selected="selected" value="">Select Style</option>
        <option value="APA">APA</option>
        <option value="Chicago">Chicago</option>
        <option value="Harvard">Harvard</option>
        <option value="MLA">MLA</option>
        <option value="Oxford">Oxford</option>
</select>

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

@Html.DropDownListFor(m => m.paperStyle, Model.paperStyleList.Select(item => new SelectListItem { Value = item, Text = item }), "Select Style")

或者这个:

@Html.DropDownListFor(m => m.paperStyle, new SelectList(Model.paperStyleList), "Select Style")

其中paperStyle是您模型的属性,paperStyleList是您的列表,其中包含IEnumerableList类型的值(APA,芝加哥等)< / p>

答案 1 :(得分:0)

试试这个,

控制器

[HttpGet]
        public ActionResult CustomerInfo()
        {

            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem() { Text = "Chicago", Value = "Chicago", Selected = false });
            items.Add(new SelectListItem() { Text = "APA", Value = "APA", Selected = false });
            items.Add(new SelectListItem() { Text = "Harvard", Value = "Harvard", Selected = false });
            items.Add(new SelectListItem() { Text = "Oxford", Value = "Oxford", Selected = false });

            ViewBag.paperStyle= new SelectList(items, "Value", "Text");
            return View();
        }

查看

@Html.DropDownList("CustomerId", (SelectList)ViewBag.paperStyle, "--Select--")