mrN
mrN

Reputation: 3774

How to pass a List(Of <Model>) as SelectListItems For DropDownList HTML Helper?

I have Model to represent User. I have created a helper class to return a set of these Users, as List(Of Users).

Here is how I do that

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

I grab them, and send them to view to from the controller like this:

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

Now, Model has two properties Id and UserName I would like to use as a value and text respectively.

I tried something like this, but this gives type casting problems. SO I am obviously doing it wrong.

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

How to pass the List as SelectListItems to the DropDownList?

Upvotes: 0

Views: 510

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

You could use LINQ to project your List(Of User) into an IEnumerable(Of SelectListItem):

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

or you could also use the SelectList constructor:

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

and inside your view:

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

but I would rather recommend you using view models instead of ViewData.

Upvotes: 1

Related Questions