如何将类放入Html.Dropdownlist中?

3

我有一个奇怪的问题,但它让我很困扰。我有这个CSS类:

class="form-control"

我需要在我的下拉菜单中使用它:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() { Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), (SelectList)ViewBag.DropList)
2个回答

6

看起来您正在尝试设置DropDownList助手中的SelectListSelectedValue,但这是不可能的。

您必须在创建SelectList时设置SelectedValue属性。请参见以下示例。

ViewBag.DropList = new SelectList(new[]{
    new SelectListItem{ Text="one", Value="1"},
    new SelectListItem{ Text="two", Value="2"},
    new SelectListItem{ Text="three", Value="3"}
    }, "Value", "Text", 2);

在以上代码中,我已经在初始化SelectList时将2设置为选定项目。之后,您可以按照以下方式传递SelectList和HTML属性。
@Html.DropDownList("destination", (SelectList)ViewBag.DropList, new { @class = "form-control" })

感谢您的选择!
解决方案:
@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), new{@class="form-control"})

你能帮我编辑一下控制器中的DropDownList代码吗?我已经在我的问题中发布了它... - DaniKR
这个DropDownList是否适用于CustomTypesparameters.Destination是否包含所选值? - Saranga
我已经解决了,我会在你的回答中发布解决方案。谢谢啊,你的回答很有效 :D - DaniKR
你发了吗?我没有删除任何东西。 - Saranga

1
最后一个参数可以是一个具有HTML属性的对象,查看MSDN
@Html.DropDownList("destination", ..., new { @class = "form-control" })

1
你能发布最新版本的代码吗?它是否与这些签名之一匹配?http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlist(v=vs.118).aspx - Douglas
错误信息如下:CS1928:“System.Web.Mvc.HtmlHelper<AdminRole.Models.SpremenljivkeView>”不包含“DropDownList”的定义,最佳扩展方法重载“System.Web.Mvc.Html.SelectExtensions.DropDownList(System.Web.Mvc.HtmlHelper, string, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>, string, object)”具有一些无效的参数。 - DaniKR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接