您没有将正确的参数传递给@Html.DropDownList。从这里的 MSDN 文档:http: //msdn.microsoft.com/en-us/library/dd470380 (v=vs.100).aspx
看起来您想使用以下重载:
public static MvcHtmlString DropDownList(
this HtmlHelper htmlHelper,
string name,
IEnumerable<SelectListItem> selectList,
Object htmlAttributes
)
因此,您的第一个参数是您正确的名称字符串,但是您需要 SelectList 作为您的第二个参数,您的 HtmlAttributes 作为您的第三个参数。试试这样:
<div class="editor-field">
@Html.DropDownList("StandID", ViewBag.StandID, new {style = "width:150px"})
</div>
更新:
不确定您是否将正确的东西传递到您的 ViewBag 中。您将它设置为等于一个新的 SelectList 对象,并且 DropDownList 需要一个 SelectListItems 的集合。
在你的控制器中试试这个:
var stands = db.Stands.ToList().Where(s => s.ExhibitorID == null)
.Select(s => new SelectListItem
{
Value = s.StandID.ToString(),
Text = s.Description + "-- £" + s.Rate.ToString()
});
ViewBag.StandID = stands;
更新:
这是我如何完成同样的事情。我有一个返回 IEnumerable 的静态方法,然后在我的视图中引用该方法。(对不起VB语法)
Namespace Extensions
Public Module Utilities
Public Function SalutationSelectList(Optional ByVal Salutation As String = "") As IEnumerable(Of SelectListItem)
Dim ddl As New List(Of SelectListItem)
ddl.Add(New SelectListItem With {.Text = "", .Value = "", .Selected = If(Salutation = "", True, False)})
ddl.Add(New SelectListItem With {.Text = "Mr.", .Value = "Mr.", .Selected = If(Salutation = "Mr.", True, False)})
ddl.Add(New SelectListItem With {.Text = "Ms.", .Value = "Ms.", .Selected = If(Salutation = "Ms.", True, False)})
ddl.Add(New SelectListItem With {.Text = "Mrs.", .Value = "Mrs.", .Selected = If(Salutation = "Mrs.", True, False)})
ddl.Add(New SelectListItem With {.Text = "Dr.", .Value = "Dr.", .Selected = If(Salutation = "Dr.", True, False)})
Return ddl
End Function
End Module
End Namespace
@Html.DropDownListFor(Function(org) org.Salutation, SalutationSelectList())