如何将List(Of <model>)作为SelectListItems传递给DropDownList HTML Helper?</model>

时间:2012-08-23 17:30:30

标签: asp.net vb.net asp.net-mvc-2 html-helper

我有模型来代表用户。我创建了一个帮助器类来返回这些用户的集合,List(Of Users)

我是这样做的

Function getDoctorsList() As List(Of Users)
    Dim userCollection As New List(Of Users)
    Dim sql = "SELECT * FROM " + _tblName + " WHERE usertype = 'doctor'"
    Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
    While dr.Read
        Dim user As New Users
        user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
        user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
        user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
        user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
        user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
        userCollection.Add(user)
    End While
    Return userCollection
End Function

我抓住它们,然后将它们发送给控制器,如下所示:

ViewData("LoginUserModel") = New LoginUser
ViewData("doctorList") = usersHelper.getDoctorsList

现在,Model有两个属性IdUserName我想分别用作值和文本。

我试过这样的东西,但是这会给出类型转换问题。所以我显然做错了。

<%= Html.DropDownList("doctors", ViewData("doctorList")) %>

如何将List作为SelectListItems传递给DropDownList?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ将List(Of User)投影到IEnumerable(Of SelectListItem)

ViewData("doctorList") = usersHelper
    .getDoctorsList()
    .Select(Function(x) New SelectListItem With { .Value = x.Id.ToString(), .Text = x.UserName })

或者您也可以使用SelectList构造函数:

ViewData("doctorList") = New SelectList(usersHelper.getDoctorsList(), "Id", "UserName")

并在您的视图中:

<%= Html.DropDownList(
    "doctors", 
    CType(ViewData("doctorList"), IEnumerable(Of SelectListItem))
) %>

但我建议您使用视图模型而不是ViewData